Ritwik Saini
Ritwik Saini

Reputation: 29

Printing Perfect Numbers between 1-100 using Java

I don't know what is the problem with my code. It should print all the perfect numbers between 1-100. I tried with nested for-loop, do while loop and for-loop. However, the code seems to be incorrect.

class CompProject1
{

    public static void main()

    {

        int num, sum=0;

        int i;

        for(num=1; num<100; num++)

        {

           for(int j = 1; j<=num ; j++)

           {

               if(num%j==0)

               {

                   sum = sum+j;

                }

            }

           if(sum==num)

           {

             System.out.println(sum);  

            }
        }
    }
}

Upvotes: 1

Views: 20029

Answers (8)

WJS
WJS

Reputation: 40044

Here is an alternate way of finding perfect numbers.

  • if 2p-1 is prime when p is prime. Then (2p-1)(2p-1) is a perfect number. 2p-1 is known as a Mersenne Prime
  • As these numbers get real big real fast, using BigInteger is recommended.

This computes the first 10 perfect numbers.

int N = 10;
int count = 1;
for(int i = 2; i < 10_000; i += i == 2 ? 1 : 2) {
    BigInteger val = BigInteger.valueOf(i);
    if (val.isProbablePrime(99)) {
        BigInteger mersenne1 = (BigInteger.ONE.shiftLeft(i)).subtract(BigInteger.ONE);
        if (!mersenne1.isProbablePrime(99)) {
            continue;
        }
        
        BigInteger mersenne2 = BigInteger.ONE.shiftLeft(i-1);
        System.out.printf("%3d:  %,d\n",count, mersenne1.multiply(mersenne2));
       
        if (count++ >= N) {
            break;
        }
    }   
}

prints

  1:  6
  2:  28
  3:  496
  4:  8,128
  5:  33,550,336
  6:  8,589,869,056
  7:  137,438,691,328
  8:  2,305,843,008,139,952,128
  9:  2,658,455,991,569,831,744,654,692,615,953,842,176
 10:  191,561,942,608,236,107,294,793,378,084,303,638,130,997,321,548,169,216

Upvotes: 0

Rohitashwa Polley
Rohitashwa Polley

Reputation: 1

class PERFECT
 {
    public static void main(String args[])
     {
         int i,j,S,
          for(i=1;i<=100;i++)
          {
          S=0
          for(j=1;j<i;j++)
          {
          if(i%j==0)
           S+=j;
           if (S==i)
           System.out.println(i+"is perfect");
           }
           }
           }
           }

Upvotes: 0

Rohith
Rohith

Reputation: 135

public class factors{
public static void main(String args[]){
    int sum=0;

    for(int k=2;k<=30;k++){
    for(int i=1;i<k;i++)
    {
        if(k%i==0)
            sum=sum+i;


    }
       if(k==sum)
             System.out.println(sum);


        sum=0;          //sum=0 is very important.
    }

}

}

OUTPUT

6
28

Upvotes: 0

Tyulpan Tyulpan
Tyulpan Tyulpan

Reputation: 764

1) you definitely need to reset your sum variable for every iteration, so you should do int sum = 0; in every loop.

2) you need to iterate while j <= num/2;!

3) consider using Java 8, I'll write some sample here for you.

See my example here, this is so beautiful:

public class PerfectNumbersDemo {

  public static void main(String[] args) {
    IntStream.range(1, 100)
        .filter(PerfectNumbersDemo::isPerfect)
        .forEach(System.out::println);
  }

  private static boolean isPerfect(int number) {
    return number == IntStream.rangeClosed(1, number / 2)
        .filter(i -> number % i == 0)
        .sum();
  }
}

Upvotes: 1

Vishwas Atrey
Vishwas Atrey

Reputation: 286

So, your code have some minor problems and I will try to pinpoint them out.

1.First of all your sum variable should be inside the first for loop
2. The limit upto which the second loop will run will be j<num not j<=num because, for the perfect number, the number itself shouldn't be counted in the sum.

You code will look like this.

I don't know what is the problem with my code. It should print all the perfect numbers between 1-100. I tried with nested for-loop, do while loop and for-loop. However, the code seems to be incorrect.

class CompProject1 {

public static void main()

{

     int num;

     for(num=1; num<100; num++)

     {

         int sum = 0;

         for(int j = 1; j<=num ; j++)

         {

              if(num%j==0)

              {

               sum = sum+j;

              }

       }

       if(sum==num)

       {

        System.out.println(sum);  

        }
    }
 }
}

Upvotes: 0

IsaacLevon
IsaacLevon

Reputation: 2570

You need to:

  • sum = 0 with every loop iteration
  • iterate until < num and not <= num

Here's the fixed code:

public static void main(String[] args)  {

int sum;
for(int num = 1; num < 100; num++) {

    sum = 0;

    for(int j = 1; j< num; j++) {
        if(num % j == 0) {
            sum += j;
        }
    }

    if(sum == num) {
        System.out.println(sum);
    }
}

}

Output:

6
28

Upvotes: 0

Nicholas K
Nicholas K

Reputation: 15423

Change your code to :

public static void main(String[] s1) throws Exception {
    int num, sum = 0;
    int i;
    for (num = 1; num < 100; num++) {
        for (int j = 1; j <= num - 1; j++) {   // change made here
            if (num % j == 0) {
                sum = sum + j;
            }
        }
        if (sum == num) {
            System.out.println(sum);
        }
        sum = 0;                              // change made here
    }

}

Key takeaways:

  1. Reset sum to 0 once done with inner iteration
  2. In your inner for-loop you need to check if till num - 1 and not num because every number is divisible by itself

Upvotes: 1

PinkBanter
PinkBanter

Reputation: 1976

This seems to be an assignment or homework question. You are meant to solve this by yourself and not ask it to the people on Stack overflow.

However, what you are looking for has an answer here. Beware! This code prints if the input number is perfect number or not but does not print all the numbers below 100 that could be perfect numbers. That is your homework.

Upvotes: 0

Related Questions