package perfect;
import java.math.BigInteger;
import java.util.Scanner;
public class Perfect {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the number");
BigInteger n = input.nextBigInteger();
BigInteger sum = BigInteger.valueOf(0);
BigInteger i = BigInteger.valueOf(1);
BigInteger mul = BigInteger.valueOf(1);
for(; i.compareTo(n)< 0; i.add(BigInteger.ONE))
{
if(n.mod(i).equals(BigInteger.ZERO))
{
sum = sum.add(i);
mul = mul.multiply(i) ;
}
}
if(sum == n)
{
System.out.println(n+ "=" +mul) ;
}
else
{
System.out.println("the given number " +n+ " is not a perfect
number");
}
}
}
as it has to print 6 = 1*2*3 i used BigInteger. but it is not showing any error but the program after taking a number from user in the console i am not getting any output.
Three problems:
BigInteger
is immutable, so you should do i = i.add(BigInteger.ONE)
insteadsum
with n
, you should do sum.equals(n)
insteadimport java.math.BigInteger;
import java.util.Scanner;
import java.util.ArrayList;
public class Perfect {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number");
BigInteger n = input.nextBigInteger();
BigInteger sum = BigInteger.valueOf(0);
BigInteger i = BigInteger.valueOf(1);
ArrayList<BigInteger> factors = new ArrayList<BigInteger>();
for (; i.compareTo(n) < 0; i = i.add(BigInteger.ONE)) {
if (n.mod(i).equals(BigInteger.ZERO)) {
sum = sum.add(i);
factors.add(i);
}
}
if (sum.equals(n)) {
System.out.print(n + "=" + factors.get(0));
for (int idx = 1; idx < factors.size(); idx++) {
System.out.print("*" + factors.get(idx));
}
System.out.println();
} else {
System.out.println("the given number " + n + " is not a perfect number");
}
}
}