
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

I am getting closer now I just need to figure out how to get rid of the 1 and get the 6 back. 1 is not a perfect number but 6 is. Here is what I have now.
public class Perfect
{
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<= limit; i++)
{
int sum=0;
for (int j=1; j<=Math.ceil(Math.sqrt(i)); j++)
{
if (i%j==0)
{
sum+=j;
//System.out.println(i+"i"+j+"j"+i/j+"t"+sum);
if ((i/j)>Math.floor(Math.sqrt(i))&& (i/j)<i)
sum+=(i/j);
}
}
if (sum==i) System.out.println(i);
}
}//end main method
}//end class

lift loop invariants
Code:
class Demo
{
int index=0;
int sum=0;
int limit Math.ceil(Math.sqrt(i));
for(index; index < limit; index++)
{
.... code goes here ....;//move loop control variables as shown.
}
}
continue work. A for loop is just sugar coated sytax for int limit = setLimit(); then do code while index not exceed some limit value.

I don't think I am following you on this one. If I make the suggested change then what will i reference to? In my code it was connected to the control loop. I guess I am confused as to which for loop you are changing.

move Math.ceil(Math.sqrt(i)); out of whichever loop it is a limit for.