Perfect number in Java


 

Perfect Number:-  If the sum of all the factors of a number is equal to the number itself then it is a perfect number. For example, 6 is a perfect number since the sum of its divisors (1 + 2 + 3) is equal to 6. This program finds whether a given number is perfect number or not..

 

 

 

 

 

 

Java Program to find if a Number is Perfect or not   

 

 

import java.io.*;

import java.util.*;

class perfectnumber

{

public static void main(String[] args) throws IOException

{

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.print(“\nEnter a number:”);

int n = Integer.parseInt(br.readLine());

int sum = 0;

for(int i=1;i<n;i++)

{

if(n%i==0)

{

sum = sum + i;

}

}

if(sum == n)

System.out.println(“\nGiven number is a perfect number”);

else

System.out.println(“\nGiven number is not perfect number”);

}

}

output:

per

 

 

 

 

 

 

 

 

 

 

 

 

 

Java Program to find list of Perfect Numbers in a Given range

 

import java.io.*;

class perfect2

{

public static void main(String[] args) throws IOException

{

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.print(“\nEnter the range:”);

long range = Long.parseLong(br.readLine());

System.out.println(“\nThe perfect numbers between 1 and “+range+” are:”);

for(int i=1;i<range;i++)

{

int sum = 0;

{

for(int j=1;j<i;j++)

{

if(i%j == 0)

{

sum = sum + j;

}

}

if(sum == i)

{

System.out.println(i);

}

}

}

}

}

output:

per2

Related Posts

Comments are closed.