How to resolve the algorithm Sum digits of an integer step by step in the F# 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 F# 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 F# programming language
Source code in the fsharp programming language
open System
let digsum b n =
let rec loop acc = function
| n when n > 0 ->
let m, r = Math.DivRem(n, b)
loop (acc + r) m
| _ -> acc
loop 0 n
[<EntryPoint>]
let main argv =
let rec show = function
| n :: b :: r -> printf " %d" (digsum b n); show r
| _ -> ()
show [1; 10; 1234; 10; 0xFE; 16; 0xF0E; 16] // -> 1 10 29 29
0
//Sum Digits of An Integer - Nigel Galloway: January 31st., 2015
//This code will work with any integer type
let inline sumDigits N BASE =
let rec sum(g, n) = if n < BASE then n+g else sum(g+n%BASE, n/BASE)
sum(LanguagePrimitives.GenericZero<_>,N)
You may also check:How to resolve the algorithm Almkvist-Giullera formula for pi step by step in the ARM Assembly programming language
You may also check:How to resolve the algorithm Modular inverse step by step in the Scala programming language
You may also check:How to resolve the algorithm Fibonacci sequence step by step in the MUMPS programming language
You may also check:How to resolve the algorithm Anagram generator step by step in the Raku programming language
You may also check:How to resolve the algorithm Sorting algorithms/Selection sort step by step in the Oz programming language