Issue
class Perfect{
public static void main(){
long a[]=new long[10];
long n=1;
for(int i=0;i<10;i++){
while(true){
long sum=0;
for(long j=1;j<n;j++){
if(n%j==0){
sum+=j;
}
}
if(sum==n){
a[i]=n;
n++;
System.out.println("The array at turn "+i);
for(int v=0;v<a.length;v++)
{
System.out.println(a[v]+" ");
}
break;
}
n++;
}
}
for(int i=0;i<a.length;i++){
System.out.print(a[i]+" ");
}
}
}
I got a program as a part of my school project to create an array of size 10 and then fill this array with perfect numbers automatically in BlueJ. I wrote the above code however for some reason the code is running for 4 times only and then going on infinity and asking for inputs and not completing the 10 loops. Can someone please help me identify the problem. The code is in Java in BlueJ
Solution
You can see here what are perfect numbers and their values: https://byjus.com/maths/perfect-numbers/
Now, I checked your code and reason why you're getting only 4 numbers (6, 28, 496 and 8128) is because your algorithm is slow. If you pay closer attention, you would see that your application is still running although you're not getting any new numbers after 8128. So if you let your program run long enough, you would generate new number: 33550336. And due to slow generation of a numbers, if you let your application run for days for example, you would generate number 8589869056 and after a few more days you would generate 137438691328 and that would be it, your application would break.
Reason for that is because next number would be: 2305843008139952128 and that number cannot be placed inside of a long type (your sum variable) because long can accept this range:
Java Long primitive type maximum limit
You can add this line in your IDE:
long outOfRangeNumber = 9223372036854775808L;
And read the error on that line.
So in theory, with your code you can only generate 7 real numbers (from 6 to 137438691328) but that generation would take days, maybe weeks even, depending on power of your machine.
Answered By - JustQuest
Answer Checked By - Pedro (JavaFixing Volunteer)