Perfect numbers: Difference between revisions
(added python) |
mNo edit summary |
||
Line 2: | Line 2: | ||
A number is perfect if the sum of its factors is equal to twice the number. An equivalent condition is that <tt>n</tt> is perfect if the sum of <tt>n</tt>'s factors that are less than <tt>n</tt> is equal to <tt>n</tt>. |
A number is perfect if the sum of its factors is equal to twice the number. An equivalent condition is that <tt>n</tt> is perfect if the sum of <tt>n</tt>'s factors that are less than <tt>n</tt> is equal to <tt>n</tt>. |
||
Maybe this can make use of solutions from our [[Prime decomposition]] task? |
|||
=={{header|BASIC}}== |
=={{header|BASIC}}== |
Revision as of 04:55, 23 August 2008
You are encouraged to solve this task according to the task description, using any language you may know.
Write a function which says whether a number is perfect.
A number is perfect if the sum of its factors is equal to twice the number. An equivalent condition is that n is perfect if the sum of n's factors that are less than n is equal to n.
Maybe this can make use of solutions from our Prime decomposition task?
BASIC
<qbasic>FUNCTION perf(n) sum = 0 for i = 1 to n - 1 IF n MOD i = 0 THEN sum = sum + i END IF NEXT i IF sum = n THEN perf = 1 ELSE perf = 0 END IF END FUNCTION</qbasic>
Java
<java>public static boolean perf(int n){ int sum= 0; for(int i= 1;i < n;i++){ if(n % i == 0){ sum+= i; } } return sum == n; }</java> Or for arbitrary precision: <java>import java.math.BigInteger;
public static boolean perf(BigInteger n){ BigInteger sum= BigInteger.ZERO; for(BigInteger i= BigInteger.ONE; i.compareTo(n) < 0;i=i.add(BigInteger.ONE)){ if(n.mod(i).compareTo(BigInteger.ZERO) == 0){ sum= sum.add(i); } } return sum.compareTo(n) == 0; }</java>
Python
<python>def perf(n):
sum = 0 for i in xrange(1,n): if n % i == 0: sum += i return sum == n</python>