下面代码需要uses math,sysutils; -- 如果有规定不让用,可以再编写两个函数;如果不需要输入保护,可以修改。program number_guess;
uses math, sysutils;
function factorial(const n : Integer) : Int64;
var
i : Integer;
begin
if n = 0 then exit(1);
factorial := 1;
for i := 2 to n do
factorial *= i;
end;
var
sum, s, sum_of_fact, r_min, r_max : Int64;
i, j, n, num, errcode : Integer;
res, instr : String;
begin
repeat
readln(instr);
val(instr, n, errcode);
if (errcode = 0) and (n in [2..11]) then break;
writeln('Invalid number, try again.');
until 1=0;
repeat
readln(instr);
val(instr, s, errcode);
if (errcode = 0) and (s > 0) then break;
writeln('Invalud number, try again.');
until 1=0;
res := 'not found';
r_min := 1;
r_max := trunc(power(10,n))-1;
for i := r_min to r_max do
begin
sum := 0; num := i;
while (num > 0) do begin sum += num mod 10; num := num div 10;end;
sum *= factorial(n-1);
sum_of_fact := 0;
for j := 0 to n-1 do sum_of_fact += sum * trunc(power(10,j));
if sum_of_fact - i = s then
begin
res := Format('%.*d',[n,i]);
break;
end;
end;
writeln(res);
end.运行:3
1209
123
-------
4
45440
1222
-------
2
90
90
------
2
100
not found
------
1
Invalid number, try again.
2
-10
Invalud number, try again.
91
19