0
Can any one know how to print first 10 perfect numbers in Java? Any one know please help me.
4 Antworten
+ 2
Perfect Number: is a number that can be written as the sum of its factors, excluding the number itself.
For example, 6 is a perfect number, since 1 + 2 + 3 = 6, where 1, 2, and 3 are all factors of 6. Similarly, 28 is a perfect number, since 1 + 2 + 4 + 7 + 14 = 28.
Example:
Input - 28
Output - true
Input - 12
Output - false
+ 1
Srinivas vedullapalli you can use just int type. Long also works. If it not working then , you can share your attempt here. So it helps to find mistake if any.
0
I know how to find perfect numbers but i want first 10 perfect numbers ,l don't know which keyword use to find that, I'm using int and long keywords but I'm not get 10 perfect numbers.
0
You can try this:
public class PerfectNumbers {
    public static void main(String[] args) {
        int count = 0;
        int number = 2;
        while (count < 10) {
            if (isPerfect(number)) {
                System.out.println(number);
                count++;
            }
            number++;
        }
    }
    public static boolean isPerfect(int number) {
        int sum = 0;
        for (int i = 1; i < number; i++) {
            if (number % i == 0) {
                sum += i;
            }
        }
        return sum == number;
    }
}



