(Perfect Numbers) A positive integer is called a perfect number if it is equal to the sum of all of its positive divisors, excluding itself. For example, 6 is the first perfect number because 6=3+2+1. The next is 28=14+7+4+2+1. There are four perfect numbers less than 10000. Write a program to find all these four numbers.
PerfectNumbers.java
/** * The perfect numbers less than 10000. */ public class PerfectNumbers { public static void main(String[] args) { int number = 1; int sum,divisor,result; String perfect = ""; // (START) The first way (With while loop). while(number<=10000){ sum = 0; // reset sum. divisor=1; // reset divisor. while(divisor<=number/2){ result = number%divisor; if(result==0){ sum+=divisor; } divisor++; } // while loop end. divisor<=number/2 if(sum==number){ perfect += " "+number; } number++; } // while loop end. number<=10000 // (END) The first way (With while loop). // (START) The second way (With for loop). /* for(;number<=10000;number++){ sum = 0; for(divisor=1;divisor<=number/2;divisor++){ result = number%divisor; if(result==0){ sum=sum+divisor; } } if(sum==number){ perfect += " "+number; } } */ // (END) The second way (With for loop). // Print perfect numbers. System.out.print("The perfect numbers less than 10000 are"+perfect+"."); } // End of main method. } // End of class.
Yorum Yok:
Yorum Yap:
Yorum yapabilmek için giriş yapmalısınız.