QuestionAsk Questions?

The number 6 is said to be a perfect number because it is equal to the sum of all its exact divisors (other than itself).

6 = 1 + 2 + 3

Write a java program that finds and prints the three smallest perfect numbers. Use methods

6 = 1 + 2 + 3

Write a java program that finds and prints the three smallest perfect numbers. Use methods

View Answers

March 23, 2010 at 10:33 AM

Hi Friend,

Try the following code:

public class PerfectNumber{

public static void main(String[]args){

int sum=0, x=0;

for(int num=1;num<500;num++){

for(int i=1;i<num;i++){

x=num%i;

if(x==0)

sum=sum+i;

}

if(sum==num){

System.out.println("Perfect Number is: "+num);

System.out.println("Factors are: ");

for(int i=1;i<num;i++){

x=num%i;

if(x==0)

System.out.println(i);

}

}

sum=0;

}

}

}

Thanks

Try the following code:

public class PerfectNumber{

public static void main(String[]args){

int sum=0, x=0;

for(int num=1;num<500;num++){

for(int i=1;i<num;i++){

x=num%i;

if(x==0)

sum=sum+i;

}

if(sum==num){

System.out.println("Perfect Number is: "+num);

System.out.println("Factors are: ");

for(int i=1;i<num;i++){

x=num%i;

if(x==0)

System.out.println(i);

}

}

sum=0;

}

}

}

Thanks

Related Tutorials/Questions & Answers:

Advertisements