How to resolve the algorithm Narcissistic decimal number step by step in the Prolog programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Narcissistic decimal number step by step in the Prolog programming language
Table of Contents
Problem Statement
A Narcissistic decimal number is a non-negative integer,
n
{\displaystyle n}
, that is equal to the sum of the
m
{\displaystyle m}
-th powers of each of the digits in the decimal representation of
n
{\displaystyle n}
, where
m
{\displaystyle m}
is the number of digits in the decimal representation of
n
{\displaystyle n}
.
Narcissistic (decimal) numbers are sometimes called Armstrong numbers, named after Michael F. Armstrong. They are also known as Plus Perfect numbers.
Generate and show here the first 25 narcissistic decimal numbers.
Note:
0
1
= 0
{\displaystyle 0^{1}=0}
, the first in the series.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Narcissistic decimal number step by step in the Prolog programming language
Source code in the prolog programming language
digits(0, []):-!.
digits(N, [D|DList]):-
divmod(N, 10, N1, D),
digits(N1, DList).
combi(0, _, []).
combi(N, [X|T], [X|Comb]):-
N > 0,
N1 is N - 1,
combi(N1, [X|T], Comb).
combi(N, [_|T], Comb):-
N > 0,
combi(N, T, Comb).
powSum([], _, Sum, Sum).
powSum([D|DList], Pow, Acc, Sum):-
Acc1 is Acc + D^Pow,
powSum(DList, Pow, Acc1, Sum).
armstrong(Exp, PSum):-
numlist(0, 9, DigList),
(Exp > 1 ->
Min is 10^(Exp - 1)
; Min is 0
),
Max is 10^Exp - 1,
combi(Exp, DigList, Comb),
powSum(Comb, Exp, 0, PSum),
between(Min, Max, PSum),
digits(PSum, DList),
sort(0, @=<, DList, DSort), % hold equal digits
( DSort = Comb;
PSum =:= 0, % special case because
Comb = [0] % DList in digits(0, DList) is [] and not [0]
).
do:-between(1, 7, Exp),
findall(ArmNum, armstrong(Exp, ArmNum), ATemp),
sort(ATemp, AList),
writef('%d -> %w\n', [Exp, AList]),
fail.
do.
You may also check:How to resolve the algorithm 4-rings or 4-squares puzzle step by step in the Java programming language
You may also check:How to resolve the algorithm Conditional structures step by step in the SNUSP programming language
You may also check:How to resolve the algorithm Active Directory/Search for a user step by step in the REXX programming language
You may also check:How to resolve the algorithm Doomsday rule step by step in the Phix programming language
You may also check:How to resolve the algorithm Angles (geometric), normalization and conversion step by step in the J programming language