How to resolve the algorithm Sum digits of an integer step by step in the Prolog 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 Prolog 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 Prolog programming language
Source code in the prolog programming language
digit_sum(N, Base, Sum):-
digit_sum(N, Base, Sum, 0).
digit_sum(N, Base, Sum, S1):-
N < Base,
!,
Sum is S1 + N.
digit_sum(N, Base, Sum, S1):-
divmod(N, Base, M, Digit),
S2 is S1 + Digit,
digit_sum(M, Base, Sum, S2).
test_digit_sum(N, Base):-
digit_sum(N, Base, Sum),
writef('Sum of digits of %w in base %w is %w.\n', [N, Base, Sum]).
main:-
test_digit_sum(1, 10),
test_digit_sum(1234, 10),
test_digit_sum(0xfe, 16),
test_digit_sum(0xf0e, 16).
You may also check:How to resolve the algorithm Special characters step by step in the PicoLisp programming language
You may also check:How to resolve the algorithm Real constants and functions step by step in the Jsish programming language
You may also check:How to resolve the algorithm Split a character string based on change of character step by step in the zkl programming language
You may also check:How to resolve the algorithm Percentage difference between images step by step in the Racket programming language
You may also check:How to resolve the algorithm Multifactorial step by step in the J programming language