Coding Practice

Write a Java program to print all Perfect numbers between 1 to n

Print all Perfect numbers between 1 to n
Sample Output
Print all Perfect numbers between 1 to n.

Enter a number: 10000
6
28
496
8128
Java-Source Code
//package loopinjava;

import java.util.Scanner;

public class Main33 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        int i, j, number, newNumber = 0;
        System.out.println("Print all Perfect numbers between 1 to n.\n");

        System.out.print("Enter a number: ");
        number = input.nextInt();

        for (i = 1; i < number; i++) {
            newNumber = 0;

            for (j = 1; j < i; j++) {
                
                if (i % j == 0) {
                    newNumber = newNumber + j; //Or, newNumber += j;
                }
            }
            if (i == newNumber) {
                System.out.println(i);
            }
        }
    }
}
Sample Output
Print all Perfect numbers between 1 to n.

Enter a number: 100
6
28

No comments:

Post a Comment

Change Theme
X