RosettaCodeData/Task/Erd-s-Nicolas-numbers/Mathematica/erd-s-nicolas-numbers.math
2025-08-11 18:05:26 -07:00

28 lines
673 B
Text

On[Assert];
isErdosNicolasWithK[n_] := Module[{d, len, k},
Assert[n > 2];
(* Get all divisors except n itself *)
d = Most[Divisors[n]];
len = Length[d];
(* Check if we have at least 2 divisors and their sum > n *)
If[len < 2 || Total[d] <= n, Return[{False, 0}]];
(* Check if sum of first k divisors equals n for some k *)
For[k = 2, k <= len, k++,
If[Total[Take[d, k]] == n, Return[{True, k}]]
];
{False, 0}
]
(* Main loop to find Erdős-Nicolas numbers *)
Do[
{isEN, k} = isErdosNicolasWithK[n];
If[isEN,
Print[StringPadLeft[ToString[n], 8] <> " equals the sum of its first " <> ToString[k] <> " divisors."]
],
{n, 3, 2000000}
]