Perfect numbers: Difference between revisions

From Rosetta Code
Content added Content deleted
(Created with new task category option, added Java)
 
Line 4: Line 4:


=={{header|Java}}==
=={{header|Java}}==
<java>public static boolean perfI(int n){
<java>public static boolean perf(int n){
int sum= 0;
int sum= 0;
for(int i= 1;i < n;i++){
for(int i= 1;i < n;i++){

Revision as of 22:49, 22 August 2008

Task
Perfect numbers
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.

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>