简体   繁体   English

使用 Java 打印 1-100 之间的完美数字

[英]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.它应该打印 1-100 之间的所有完美数字。 I tried with nested for-loop, do while loop and for-loop.我尝试使用嵌套的 for 循环、while 循环和 for 循环。 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);  

            }
        }
    }
}

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完成内部迭代后将sum重置为 0
  2. In your inner for-loop you need to check if till num - 1 and not num because every number is divisible by itself在您的内部for-loop您需要检查是否直到num - 1而不是num因为每个数字都可以被自身整除

1) you definitely need to reset your sum variable for every iteration, so you should do int sum = 0; 1) 你肯定需要为每次迭代重置你的 sum 变量,所以你应该做int sum = 0; in every loop.在每个循环中。

2) you need to iterate while j <= num/2; 2) 你需要迭代而j <= num/2; !

3) consider using Java 8, I'll write some sample here for you. 3)考虑使用Java 8,我会在这里为你写一些示例。

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

You need to:你需要:

  • sum = 0 with every loop iteration sum = 0每次循环迭代
  • iterate until < num and not <= num迭代直到< num而不是<= 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 6
28 28

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.此代码打印输入的数字是否为完全数,但不会打印 100 以下的所有可能是完全数的数字。 That is your homework.那是你的功课。

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 1.首先你的 sum 变量应该在第一个 for 循环内
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. 2. 第二个循环运行的极限将是j<num而不是j<=num因为对于完全数,数字本身不应计入总和。

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.它应该打印 1-100 之间的所有完美数字。 I tried with nested for-loop, do while loop and for-loop.我尝试使用嵌套的 for 循环、while 循环和 for 循环。 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);  

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

Here is an alternate way of finding perfect numbers .这是寻找完美数字的另一种方法。

  • if 2 p -1 is prime when p is prime.如果2 p -1是质数,当p是质数时。 Then (2 p-1 )(2 p -1) is a perfect number.那么(2 p-1 )(2 p -1)是一个完美数。 2 p -1 is known as a Mersenne Prime 2 p -1被称为梅森素数
  • As these numbers get real big real fast, using BigInteger is recommended.由于这些数字很快就会变得非常大,因此建议使用BigInteger

This computes the first 10 perfect numbers.这将计算前 10 个完美数字。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM