How to resolve the algorithm Sum digits of an integer step by step in the ATS programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Sum digits of an integer step by step in the ATS programming language
Table of Contents
Problem Statement
Take a Natural Number in a given base and return the sum of its digits:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Sum digits of an integer step by step in the ATS programming language
Source code in the ats programming language
(* ****** ****** *)
//
// How to compile:
// patscc -DATS_MEMALLOC_LIBC -o SumDigits SumDigits.dats
//
(* ****** ****** *)
//
#include
"share/atspre_staload.hats"
//
(* ****** ****** *)
extern
fun{a:t@ype}
SumDigits(n: a, base: int): a
implement
{a}(*tmp*)
SumDigits(n, base) = let
//
val base = gnumber_int(base)
//
fun
loop (n: a, res: a): a =
if gisgtz_val (n)
then loop (gdiv_val(n, base), gadd_val(res, gmod_val(n, base)))
else res
//
in
loop (n, gnumber_int(0))
end // end of [SumDigits]
(* ****** ****** *)
val SumDigits_int = SumDigits
(* ****** ****** *)
implement
main0 () =
{
//
val n = 1
val () = println! ("SumDigits(1, 10) = ", SumDigits_int(n, 10))
val n = 12345
val () = println! ("SumDigits(12345, 10) = ", SumDigits_int(n, 10))
val n = 123045
val () = println! ("SumDigits(123045, 10) = ", SumDigits_int(n, 10))
val n = 0xfe
val () = println! ("SumDigits(0xfe, 16) = ", SumDigits_int(n, 16))
val n = 0xf0e
val () = println! ("SumDigits(0xf0e, 16) = ", SumDigits_int(n, 16))
//
} (* end of [main0] *)
You may also check:How to resolve the algorithm Palindrome detection step by step in the Maxima programming language
You may also check:How to resolve the algorithm Palindromic gapful numbers step by step in the Raku programming language
You may also check:How to resolve the algorithm Power set step by step in the CoffeeScript programming language
You may also check:How to resolve the algorithm Literals/String step by step in the Nim programming language
You may also check:How to resolve the algorithm Taxicab numbers step by step in the Ring programming language