
Patrick B. answered 07/22/21
Math and computer tutor/teacher
import java.util.ArrayList;
import java.util.Scanner;
class PerfectNumber
{
private Scanner scanner;
PerfectNumber() { scanner = new Scanner(System.in); }
//returns the arrayList of factors of N, including 1 but not N;
// ex. GetFactors(32,factors); ---> factors = {1,2,4,8,16}
public void GetFactors(long N, ArrayList<Long> factors)
{
factors.add(1L);
for (long iLoop=2; iLoop<N/2+1; iLoop++)
{
if (N % iLoop==0)
{
factors.add(iLoop);
}
}
}
boolean IsPerfectNumber( long nLongIntNum, ArrayList<Long> factors)
{
GetFactors(nLongIntNum,factors);
int N = factors.size();
boolean booleanReturn=false;
long sumFactors = 0;
for (int iLoop=0; iLoop<N; iLoop++)
{
sumFactors += (long) factors.get(iLoop);
}
return (booleanReturn = (sumFactors==nLongIntNum));
}
void DisplayPerfectNumber( long nLongIntNum, ArrayList<Long> factors)
{
System.out.print( nLongIntNum + " is a perfect number. It's factors are :");
int N = factors.size();
for (int iLoop=0; iLoop<N; iLoop++)
{
System.out.print(factors.get(iLoop)+ " ");
}
System.out.println("");
}
public void Go()
{
long N=-1;
ArrayList<Long> factors = new ArrayList<Long>();
// 2 and 3 are not perfect numbers
while (N<3)
{
System.out.print(" Enter the number up to which you would like to look for perfect numbers :>");
N = scanner.nextLong();
}
System.out.println("Scanning for perfect numbers between 2 and " + N);
for (long iLoop=3; iLoop<=N; iLoop++)
{
if (iLoop%10000==0) { System.out.println(" checking " + iLoop + "...."); }
if (IsPerfectNumber(iLoop,factors))
{
DisplayPerfectNumber(iLoop,factors);
}
factors.clear();
}
}
public static void main (String args[])
{
new PerfectNumber().Go();
}
}