1

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);  

            }
        }
    }
}
Nicholas K
  • 15,148
  • 7
  • 31
  • 57
Ritwik Saini
  • 29
  • 1
  • 1
  • 5

8 Answers8

1

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
Nicholas K
  • 15,148
  • 7
  • 31
  • 57
  • He should actually iterate to num/2, your answer is fine for fixing the problem he faced, but not so good in case of optimization – Tyulpan Tyulpan May 30 '19 at 14:29
  • What optimization do *you* need to print perfect numbers from 1-100? It wouldn't make any difference. Your down-vote is ridiculous. – Nicholas K May 30 '19 at 16:03
  • How can you even know it's mine? The thing is not even about optimization, it's about correct math-model. – Tyulpan Tyulpan May 30 '19 at 16:09
  • What if he's gonna need to evaluate the values of first 1.000.000 numbers? – Tyulpan Tyulpan May 30 '19 at 16:10
  • 1. Pretty obvious that you down-voted it (Since there was a comment at the very same time) 2. Why should I care if its till 1,000,000? Question clearly states 1 - 100. This is also **not** a question on performance. – Nicholas K May 30 '19 at 16:14
  • 2. Coz you're smart dude (I hope so), so you should have seen this mistake. – Tyulpan Tyulpan May 30 '19 at 16:16
1

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();
  }
}
Tyulpan Tyulpan
  • 724
  • 1
  • 7
  • 17
0

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

IsaacLevon
  • 2,260
  • 4
  • 41
  • 83
0

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.

PinkBanter
  • 1,686
  • 5
  • 17
  • 38
0

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);  

        }
    }
 }
}
Vishwas Atrey
  • 286
  • 3
  • 9
0
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
Rohith
  • 135
  • 1
  • 10
0
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");
           }
           }
           }
           }
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 21 '23 at 21:34
0

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
WJS
  • 36,363
  • 4
  • 24
  • 39