How to resolve the algorithm Munchausen numbers step by step in the Modula-2 programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Munchausen numbers step by step in the Modula-2 programming language
Table of Contents
Problem Statement
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance: 3435 = 33 + 44 + 33 + 55
Find all Munchausen numbers between 1 and 5000.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Munchausen numbers step by step in the Modula-2 programming language
Source code in the modula-2 programming language
MODULE MunchausenNumbers;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,ReadChar;
(* Simple power function, does not handle negatives *)
PROCEDURE Pow(b,e : INTEGER) : INTEGER;
VAR result : INTEGER;
BEGIN
IF e=0 THEN
RETURN 1;
END;
IF b=0 THEN
RETURN 0;
END;
result := b;
DEC(e);
WHILE e>0 DO
result := result * b;
DEC(e);
END;
RETURN result;
END Pow;
VAR
buf : ARRAY[0..31] OF CHAR;
i,sum,number,digit : INTEGER;
BEGIN
FOR i:=1 TO 5000 DO
(* Loop through each digit in i
e.g. for 1000 we get 0, 0, 0, 1. *)
sum := 0;
number := i;
WHILE number>0 DO
digit := number MOD 10;
sum := sum + Pow(digit, digit);
number := number DIV 10;
END;
IF sum=i THEN
FormatString("%i\n", buf, i);
WriteString(buf);
END;
END;
ReadChar;
END MunchausenNumbers.
You may also check:How to resolve the algorithm Leap year step by step in the Fōrmulæ programming language
You may also check:How to resolve the algorithm Damm algorithm step by step in the C# programming language
You may also check:How to resolve the algorithm Set step by step in the Dart programming language
You may also check:How to resolve the algorithm Ackermann function step by step in the Mercury programming language
You may also check:How to resolve the algorithm 100 doors step by step in the Retro programming language