Given an integer input as the number, the objective is to check whether or not the number can be represented as the sum of its factors except the number itself. Therefore, we write a code to Check Whether or Not a Number is a Perfect Number in Java Language
Perfect Number
A Perfect Number is a positive integer that equals the sum of its proper divisors (factors excluding the number itself).
For example:
- 6 is a perfect number because .
- 28 is also a perfect number because .
import java.util.*;
class HelloWorld {
public static void main(String[] args) {
int n=sc.nextInt();
int sum=0;
for(int i=1;i<n;i++){
if(n%i==0){
sum+=i;
}
}
System.out.print(n%sum==0?"yes":"no");
}
}
}
How It Works
Input:
The program reads an integer from the user.Find Proper Divisors:
- A proper divisor of is any number less than that divides without a remainder.
- Use a
forloop from 1 to to check all possible divisors.
Sum the Divisors:
- Add each divisor to a variable
sum.
- Add each divisor to a variable
Check for Perfection:
- Compare
sumwith . - If
sum == n, the number is perfect; otherwise, it’s not.
- Compare
Output:
- Print "Yes" if the number is perfect, and "No" otherwise.
Example Input and Output
Example 1
Input:
6
Process:
- Proper divisors of 6 are .
- Sum = .
Output:
Example 2
Input:
10
Process:
- Proper divisors of 10 are .
- Sum = .
Output:
Edge Cases
Smallest Perfect Number:
The smallest perfect number is 6.Prime Numbers:
Prime numbers can never be perfect numbers because their only proper divisor is 1.Negative Numbers:
Perfect numbers are defined only for positive integers.
No comments:
Post a Comment