Perfect Number: a perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself.
package demo;
import java.util.Scanner;
public class PerfectNumber
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n, i = 1, sum = 0;
System.out.print("Enter a number: ");
n = sc.nextInt();
while (i < n) {
if (n % i == 0) {
sum = sum + i;
}
i++;
}
if (sum == n) {
System.out.print(i + " is a perfect number");
} else {
System.out.print(i + " is not a perfect number");
}
}
}
Output: Java program to find perfect numbers
Enter a number: 6
6 is a perfect number
BUILD SUCCESSFUL (total time: 36 seconds)
package demo;
import java.util.Scanner;
public class PerfectNumber
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n, i = 1, sum = 0;
System.out.print("Enter a number: ");
n = sc.nextInt();
while (i < n) {
if (n % i == 0) {
sum = sum + i;
}
i++;
}
if (sum == n) {
System.out.print(i + " is a perfect number");
} else {
System.out.print(i + " is not a perfect number");
}
}
}
Output: Java program to find perfect numbers
Enter a number: 6
6 is a perfect number
BUILD SUCCESSFUL (total time: 36 seconds)
|
No comments:
Post a Comment