Efficient Perfect Number
I have code written to discover perfect numbers but my instructor wants me to make it work more efficiently. I understand what needs to happen just not how to make it happen. To make it faster I need to use Math.sqrt(). The only problem is that when doing it this way I am not saving the multiple of the lower numbers. For example 28 is a perfect number. 1+2+4+7+14=28 the problem is that by using the Math.sqrt I limit the search to everything below 5.29 which I rounded up to 6. By doing this I am still missing out on 7 and 14 which are the reciprocals to 2 and 4. Is there something I can do to save these reciprocals and only go up to the square root?
Here is what I have now:
public class Perfect //MUST match the file name!
{
public static void main (String[ ] args)
{
Scanner keyboard = new Scanner(System.in);
int limit;
System.out.println("Please enter a limit for finding perfect numbers:");
limit = keyboard.nextInt();
for (int i=1; i<= Math.ceil(Math.sqrt(limit)); i++) //By just setting
//this to limit it works just slowly.
{
int sum=0;
for (int j=1; j<i; j++)
{
if (i%j==0) sum+=j;
}
if (sum==i) System.out.println(i);
}
}//end main method
}//end class
|