How to resolve the algorithm Digital root step by step in the Prolog programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Digital root step by step in the Prolog programming language

Table of Contents

Problem Statement

The digital root,

X

{\displaystyle X}

, of a number,

n

{\displaystyle n}

, is calculated: The additive persistence is the number of summations required to obtain the single digit. The task is to calculate the additive persistence and the digital root of a number, e.g.: The digital root may be calculated in bases other than 10.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Digital root 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).

digital_root(N, Base, AP, DR):-
    digital_root(N, Base, AP, DR, 0).

digital_root(N, Base, AP, N, AP):-
    N < Base,
    !.
digital_root(N, Base, AP, DR, AP1):-
    digit_sum(N, Base, Sum),
    AP2 is AP1 + 1,
    digital_root(Sum, Base, AP, DR, AP2).

test_digital_root(N, Base):-
    digital_root(N, Base, AP, DR),
    writef('%w has additive persistence %w and digital root %w.\n', [N, AP, DR]).

main:-
    test_digital_root(627615, 10),
    test_digital_root(39390, 10),
    test_digital_root(588225, 10),
    test_digital_root(393900588225, 10),
    test_digital_root(685943443231217865409, 10).


  

You may also check:How to resolve the algorithm Roman numerals/Encode step by step in the Zoea Visual programming language
You may also check:How to resolve the algorithm Determine if a string is numeric step by step in the ERRE programming language
You may also check:How to resolve the algorithm Deming's funnel step by step in the Factor programming language
You may also check:How to resolve the algorithm Mutual recursion step by step in the Clojure programming language
You may also check:How to resolve the algorithm Averages/Simple moving average step by step in the Haskell programming language