【问题标题】:How to write a loop to display multiples of primes in Java?如何编写循环以在 Java 中显示多个素数?
【发布时间】:2016-06-30 03:48:07
【问题描述】:

我的作业内容如下:

编写一个程序,找出介于 1 和您允许用户输入的某个数之间的所有质数。

  • 查找介于 0 和用户输入的数字之间的质数。
  • 打印这些质数,每行一个。
  • 在每个素数后添加一个冒号,然后打印出所有被排除的非素数。

基本上,这些非素数是素数的倍数。

例如,输出将如下所示:

2: 4 6 8 10 12 14 16 18... 
3: 9 15 21 27 

我做了素数。我不知道如何计算和显示倍数?请帮忙!

package assignment4;

import java.util.Scanner;

public class Assignment4 {   /**
 * @param args the command line arguments
 */
public static void main(String[] args) {
   Scanner s = new Scanner(System.in);
   final int START = 1;
   System.out.print("Enter the end number number : ");
   int end = s.nextInt();
     System.out.println("List of prime numbers between " + START + " and "
     + end);
       for (int i = START; i <= end; i++) {
       if (isPrime(i)) {
           System.out.println(i + ":");
       }
   }
 }

   public static boolean isPrime(int n) {
   if (n <= 1) {
       return false;
   }
   for (int i = 2; i < Math.sqrt(n); i++) {
       if (n % i == 0) {
           return false;
       }
   }
   return true;}

 }

【问题讨论】:

  • 你只需要创建一个数组并在其中插入素数...
  • 一些提示:(1)for 的第三个表达式不必是x++ 的形式。您可以有一个看起来像for (int j = 2 * i; j &lt;= end; j += i)for 循环,它每次都会将i 添加到索引中。 (2) 看起来您只能打印每个倍数一次(您在以 2 开头的行上打印 6,因此您不能在“3”行上打印它)。有几种好方法可以跟踪您已打印的数字:Set 和布尔数组。
  • 从问题的措辞,尤其是“已消除的非素数”这句话来看,我认为您的老师希望您使用埃拉托色尼筛算法来查找素数。维基百科页面在这里:en.wikipedia.org/wiki/Sieve_of_Eratosthenes
  • @OP 答案已编辑

标签: java loops


【解决方案1】:

我假设您想打印直到end 数字的倍数。您可以嵌套一个将质数相乘的while循环,如下所示:

for (int i = START; i <= end; i++) {
   if (isPrime(i)) {
       System.out.print(i + ": "); //Changed to print so that the multiples are on the same line
       int multiple = i * 2;
       while (multiple <= end) {
           multiple += i;
           System.out.print(multiple + ", ");
       }
       System.out.println("");
   }
}

【讨论】:

  • 不够好。查看“3”的预期输出:它没有 6 或 12。
  • 你用了什么end?我指定循环应该继续打印直到它到达end,但如果需要,您可以指定其他值。
【解决方案2】:

如果您使用 Erathrosthenes 筛子进行筛分,则显示倍数会很容易。您创建一个从 2 到 n 的数字数组。从 2 开始,将其所有倍数标记为非质数:2 4 6... 打印它们。选择下一个素数(即未标记为非素数的数字)即 3,标记非素数的所有倍数(尚未标记):9 15 ... 等等。

最简单的解决方案:

    boolean[] x = new boolean[N];// x[i] is true when i is not prime
    for(int i=2;i<N;i++){
        if(!x[i]){
            System.out.print(i+" : ");
            for(int j=i*i;j<N;j+=i){
                if(!x[j])
                System.out.print(j+" ");
                x[j]=true;
            }
        System.out.println();
        }
    }

【讨论】:

  • 不够好。查看“3”的预期输出:它没有 12,但您的算法会打印它。在任何情况下,我都不认为为别人做作业是个好主意。
【解决方案3】:

请检查以下答案以满足您的要求,

  package assignment4; 

  import java.util.*;
  import java.lang.*;
  import java.io.*;


  public class Assignment4
  {
          public static List<Integer> primeNumbers = new ArrayList<>();
        public static String strOtherData[];

    public static void main (String[] args) throws java.lang.Exception
      {
        final int START = 1;
        System.out.print("Enter the end number number : ");
        int end = s.nextInt();

        System.out.println("List of prime numbers between " + START + " and "  + end);

         for (int i = START; i <= end; i++) {
              if (isPrime(i)) {
                    primeNumbers.add(i);
                }
            }

          strOtherData = new String[primeNumbers.size()];

            for (int i = START; i <= end; i++) {
                isMultiple(i);
            }

          int tempCount = 0;
            for(Integer currentNumber : primeNumbers)
          {
                System.out.print(currentNumber + ": \t");

            if(strOtherData.length > tempCount)
                {
                System.out.print(strOtherData[tempCount] + "\n\n");
              }

                tempCount++;
          }
      }

      public static boolean isPrime(int n) {
          if (n <= 1) {
                  return false;
          }
          for (int i = 2; i <= n/2; i++) 
          {
              if (n % i == 0)
                {
                 return false;
              }
            }
          return true;
     }

     public static void isMultiple(int n)
     {
            if (n <= 1) {
                    return;
            }

          if(isPrime(n))
               return;

            int count = 0;
          for(Integer currentInt : primeNumbers)
            {
                if(strOtherData[count] != null)
                {
                   strOtherData[count] += "," + n;
                }
                else
                {
                    strOtherData[count] = "" + n;
                }
              count++;
          }
     }
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-19
    • 1970-01-01
    • 1970-01-01
    • 2019-02-27
    • 1970-01-01
    • 2021-08-31
    • 2019-08-27
    • 1970-01-01
    相关资源
    最近更新 更多