Respuesta :
Answer:
The answer to this question can be given as:
Program:
import java.util.*; //import package.
public class PerfectNumbers //define class.
{
public static void main(String[] args) //define main method
{
System.out.print("Enter the number up to which you would like to look for perfect numbers:"); //message
Scanner input = new Scanner(System.in); //creating scanner class Object
int user = input.nextInt(); //input from user.
for (int num = 1; num <= user; num++) //loop.
{
if (isPerfect(num)) //condittional statement.
{
System.out.println("The number " + num + " is perfectnumber");
System.out.println("It's factors are:" + isPerfect(num));
}
}
}
public static Boolean isPerfect(int num) //define function isPerfect.
{
int sum = 0,n; //define variable.
n=num;
for (int factor = 1; factor < n; factor++) /loop.
{
if (n % factor == 0)
//check conditions n modules factor is equal to 0.
{
sum =sum+ factor; //addition of factor.
}
}
if (sum == n) //check sum is equal to n.
{
return true; //return values.
}
else
{
return false;
//return values.
}
}
}
Output:
Enter the number up to which you would like to look for perfect numbers:12
The number 6 is perfect number
It's factors are:true
Explanation:
In the above program first, We import the java util package form user-input. Then we declare the class PerfectNumbers that is given in the question. Then we declare the main method in the main method we create scanner class object and declare an integer variable user that takes an input from the user we declare the for loop. In the loop, we use the conditional statement in the if block we print all the values of the isPerfect() function. Then we declare isPerfect() function this function return type is Boolean that means it returns only true or false. In this function, we pass a parameter that prints the factor of the number. In this function, we check if number and sum are equal then it returns true else it returns false.