Perfect Number Program in Java Using While Loop

The number which is equal to the sum of its divisors is called a perfect number. Read the entered long number, assigned to the long variable n. While loop iterates until the condition (i<=n/2) is false. If the remainder of n/i=0 then add i value to the sum and increase the i value. After all the iterations compare the number with the sum, if both are equal then prints the number as a perfect number.
Example:
n = 6, i = 1 condition at while is 1 <= 3 is true, here 6%i = 0 is true so sum = 1,
i = 2, 2 < 3 is true, 6%2 = 0 is true so sum = 1+2=3,
i=3, 3<=3 is true, 6%3=0 is true so sum=3+3=6, for i=4 the while loop terminates and compares the sum value with n, both are equal, so it prints 6 is a perfect number.
Implementation
Java
import java.util.Scanner;Â
class Perfect{    public static void main(String arg[])       {        long n,sum=0;                     Scanner sc=new Scanner(System.in);                   System.out.println("Enter a number");                   n=sc.nextLong();        int i=1;        while(i<=n/2)        {           if(n%i==0)           {        sum+=i;           }          i++;        }    if(sum==n)    {    System.out.println(n+" is a perfect number");               }    else    System.out.println(n+" is not a perfect number");    }} |
Output: Â Â Â Â
Â
The time complexity is O(n), where n is the input number.
The auxiliary space is O(1)
Example :
Java
import java.io.*;public class PerfectNumber {Â Â Â Â public static void main(String[] args) {Â Â Â Â Â Â Â Â int number = 1;Â
        while (number <= 10000) {            int sum = 0;Â
            // Find all the factors of the current number and add them up            for (int i = 1; i < number; i++) {                if (number % i == 0) {                    sum += i;                }            }Â
            // If the sum of the factors equals the number, it's a perfect number            if (sum == number) {                System.out.println(number + " is a perfect number");            }Â
            number++;        }    }} |
output :
6 is a perfect number 28 is a perfect number 496 is a perfect number 8128 is a perfect number



