1

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.

4

1 に答える 1

6

あなたのコードは良さそうです。あなたが忘れている唯一のことはsoma、while ループで毎回の値をリセットすることです。現在のコードでは、これまでにループしたすべてsomaの数値の適切な因数の合計です。これは、必要なものではありません。

必要なコードは次のとおりです。

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++;
}
于 2016-11-21T22:15:49.203 に答える