We consider an integer number as a perfect number if its factors (including 1, but not the number itself) total up to the number. For example, 6 is a perfect number because its factors (excluding 6) are: 1, 2, and 3, which total to 6. Write a method (also known as functions in C++) named isPerfect that takes in one parameter named number, and return a String containing the factors for the number that totals up to the number if the number is a perfect number. If the number is not a perfect number, have the method return a null string (do this with a simple: return null; statement).

Respuesta :

Answer:

import java.util.*;

public class PerfectNum{

 

public static String isPerfect(long number){

String s = "";

long sum = 0;

//Checking if the number is perfect or not

for(long i = 1; i < number; i++){

if(number % i == 0){

sum += i;

}

}

 

if(sum == number){

for(long i = 1; i < number; i++){

String t = "";

if(number % i == 0){

long n = i;

//Converting into string

while(n > 0){

long p = n % 10;

t += (char)(p + '0');

n /= 10;

}

//Reversing the number

for(int j = t.length() - 1; j >= 0; j--){

s += t.charAt(j);

}

s += " ";

}

}

}

 

return s;

}

 

public static void main(String[] args){

Scanner sc = new Scanner(System.in);

System.out.println("Enter maximum number");

long n = sc.nextLong();

System.out.println("Displaying perfect numbers 2 to " + n);

for(long i = 2; i <= n; i++){

String s = isPerfect(i);

if(s != "")

System.out.println(s +"->" + i);

}

}

}

ACCESS MORE