Danny Gomes - 7 months ago 32

Java Question

Hello this is my first time asking a question here, I read the guidelines and I did look for an answer and did not find one so I hope my question is within the guidelines. Anyway I am stuck on a simple Java exercise where I have to output the first N perfect numbers (In number theory, a perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself (also known as its aliquot sum).) So I did this

`import java.util.Scanner;`

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

int cont = 0;

int num = 1;

int soma = 0;

System.out.println("Quantos números perfeitos?");

int n = in.nextInt();

while (cont < n) {

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

if (num % i == 0) {

soma = soma + i;

}

}

if (num == soma) {

System.out.println(num + " é perfeito.");

cont++;

}

num++;

}

}

It gets stuck in an infinite loop and i can't figure out why. Anyway if someone can help me I'd really appreciate it and if my question has been answered or if it's just a stupid question sorry, as I said it is my first time asking. Thank you.

Answer

Your code looks good--the only thing you're forgetting to do is reset the value of `soma`

every time in the while loop. In your current code, `soma`

is the sum of the proper factors of *all* the numbers you looped through so far, which is not what you want.

Here's the code you would need:

```
Scanner in = new Scanner(System.in);
int cont = 0;
int num = 1;
int soma;
System.out.println("Quantos números perfeitos?");
int n = in.nextInt();
while (cont < n) {
soma = 0; //Don't forget this line
for (int i = 1; i <= num / 2; i++) {
if (num % i == 0) {
soma = soma + i;
}
}
if (num == soma) {
System.out.println(num + " é perfeito.");
cont++;
}
num++;
}
```

Source (Stackoverflow)