How to resolve the algorithm Kaprekar numbers step by step in the Modula-2 programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Kaprekar numbers step by step in the Modula-2 programming language
Table of Contents
Problem Statement
A positive integer is a Kaprekar number if: Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive.
10000 (1002) splitting from left to right:
Generate and show all Kaprekar numbers less than 10,000.
Optionally, count (and report the count of) how many Kaprekar numbers are less than 1,000,000.
The concept of Kaprekar numbers is not limited to base 10 (i.e. decimal numbers); if you can, show that Kaprekar numbers exist in other bases too.
For this purpose, do the following:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Kaprekar numbers step by step in the Modula-2 programming language
Source code in the modula-2 programming language
MODULE Kaprekar;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT Write,WriteString,WriteLn,ReadChar;
PROCEDURE kaprekar(n,base : LONGCARD) : BOOLEAN;
VAR
nn,r,tens : LONGCARD;
BEGIN
nn := n*n;
tens := 1;
IF ((nn - n) MOD (base - 1)) # 0 THEN RETURN FALSE END;
WHILE tens < n DO tens := tens * base END;
IF n = tens THEN
IF 1 = n THEN RETURN TRUE END;
RETURN FALSE
END;
LOOP
r := nn MOD tens;
IF r >= n THEN BREAK END;
IF nn DIV tens + r = n THEN RETURN tens#0 END;
tens := tens * base;
END;
RETURN FALSE
END kaprekar;
PROCEDURE print_num(n,base : LONGCARD);
VAR q,d : LONGCARD;
BEGIN
d := base;
WHILE d
LOOP
d := d DIV base;
IF n BAND d = 0 THEN RETURN END;
q := n DIV d;
IF q<10 THEN
Write(CHR(INT(q) + INT(ORD('0'))))
ELSE
Write(CHR(INT(q) + INT(ORD('a')) - 10))
END;
n := n - q * d
END
END print_num;
VAR
buf : ARRAY[0..63] OF CHAR;
i,tens,cnt,base : LONGCARD;
BEGIN
cnt := 0;
base := 10;
FOR i:=1 TO 1000000 DO
IF kaprekar(i,base) THEN
INC(cnt);
FormatString("%3u: %u\n", buf, cnt, i);
WriteString(buf)
END
END;
ReadChar
END Kaprekar.
You may also check:How to resolve the algorithm Sum multiples of 3 and 5 step by step in the Emacs Lisp programming language
You may also check:How to resolve the algorithm Pig the dice game step by step in the REXX programming language
You may also check:How to resolve the algorithm Hailstone sequence step by step in the Modula-2 programming language
You may also check:How to resolve the algorithm Compare a list of strings step by step in the PureBasic programming language
You may also check:How to resolve the algorithm Odd word problem step by step in the OCaml programming language