0
$\begingroup$

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.
Thanks in advance.

$\endgroup$
1
  • $\begingroup$ If you do not insist on procedural code, then simply define perfectNumberQ[x_Integer] := (Plus @@ Most[Divisors[x]] === x) $\endgroup$
    – Acus
    Jan 11, 2019 at 16:43

1 Answer 1

0
$\begingroup$

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"]];]
$\endgroup$
1
  • $\begingroup$ Oops..why i miss it.Really embracing.But Thanks @MassDefect Sir.I will follow this. $\endgroup$ Jan 11, 2019 at 17:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.