# Problem faced using user-defined mod function in loop

I want to make a program which tell whether a number perfect or not.So i tried like that:

mod[x_, y_] := Module[{x0 = x, y0 = y, p, q},
For[i = 1, i <= x0/y0, i++, p = i];
q = x0 - (y0*p);
q]

perfectc[n_] := Module[{n0 = n, s = 0},
For[i = 1, i <= n0, i++, If[mod[n0, i] == 0, s = s + i]];
If[s == 2*n0, Print[n0, " is a perfect number"],
Print[n0, " isn't a perfect number"]];
]


First I make mine mod[] function then use it in the perfectc[] function.But It's not working.Rather using my mod[] function if i use build-in Mod[] function the program run well.

perfectc[n_] := Module[{n0 = n, s = 0},
For[i = 1, i <= n0, i++, If[Mod[n0, i] == 0, s = s + i]];
If[s == 2*n0, Print[n0, " is a perfect number"],
Print[n0, " isn't a perfect number"]];
]


Can Anyone help me to figure out this. Any hints or solution will be appreciated.

• If you do not insist on procedural code, then simply define perfectNumberQ[x_Integer] := (Plus @@ Most[Divisors[x]] === x) – user18792 Jan 11 '19 at 16:43

I believe the issue is that your mod function increments the variable i. So you call perfectc which increments i, then it calls mod which also increments i. Try either using different incrementing variables for mod and perfectc or add them to the Module like this:

mod[x_, y_] :=
Module[{x0 = x, y0 = y, p, q, i},
For[i = 1, i <= x0/y0, i++, p = i];
q = x0 - (y0*p);
q]

perfectc[n_] :=
Module[{n0 = n, s = 0, i},
For[i = 1, i <= n0, i++, If[mod[n0, i] == 0, s = s + i]];
If[s == 2*n0, Print[n0, " is a perfect number"],
Print[n0, " isn't a perfect number"]];]

• Oops..why i miss it.Really embracing.But Thanks @MassDefect Sir.I will follow this. – emonhossain Jan 11 '19 at 17:54