简体   繁体   English

如何使用 Java 中的一种方法将质数打印到 N

[英]How to print prime numbers to N using one method in Java

I am trying to make a void method that prints prime numbers up to a given int argument.我正在尝试创建一个 void 方法,该方法将质数打印到给定的 int 参数。 This is what I have and it's not working.这就是我所拥有的,但它不起作用。

public class listPrimes {
    public static void main(String[] args) {
        printPrimes(1000);

    }

static void printPrimes(int max) {
    int counter = 0;
    for (int i = 2; i <= max; i++) {
        for (int n = 2; n < i; n++) {
            if (i % n == 0) {
                counter++;
            }
        }
        if (counter == 0) {
            System.out.println(i);
            counter = 0;
        }
    }
}
}

I was able to create the desired effect using 2 methods below but I want to do it with one.我能够使用以下两种方法创建所需的效果,但我想用一种方法来实现。 What is wrong with my code above?我上面的代码有什么问题?

public class listPrimes {
    public static void main(String[] args) {
        printPrimes(1000);
    }

private static void printPrimes(int max) {
    for (int i = 2; i <= max; i++) {
        if (primeCheck(i)) {
            System.out.println(i);
        }
    }
}

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

You never reset the value of counter in the outer loop .您永远不会outer loop重置counter的值。 So, once it is increased, it will never be 0. So, just reset counter at the beginning of the outer loop: -所以,一旦增加,它就永远不会为 0。所以,只需在外循环开始时重置counter : -

for (int i = 2; i <= max; i++) {
    counter = 0;
    for (int n = 2; n < i; n++) {
        if (i % n == 0) {
            counter++;
        }
    }
    if (counter == 0) {
        System.out.println(i);
    }
}

However, I would prefer to have the 2nd way, since it has divided the task in different method.但是,我更喜欢第二种方式,因为它以不同的方法划分了任务。 So, both the methods have their defined roles.因此,这两种方法都有其定义的角色。 And you can use them at some other place easily.您可以轻松地在其他地方使用它们。 Just remember, the more you divide task amongst different methods, the more re-usability you get.请记住,您在不同方法之间划分任务的次数越多,您获得的可重用性就越高。 It's always better to have one method do just one task.让一种方法只完成一项任务总是更好。

Also, I would suggest to rename the method - primeCheck to isPrime , since it is returning a boolean value.另外,我建议的方法重新命名- primeCheckisPrime ,因为它返回一个boolean值。 So, just to follow the naming convention, isPrime will be a good name.所以,只是为了遵循命名约定, isPrime将是一个好名字。

One variation, for better performance:一种变体,以获得更好的性能:

public static void main(String[] args) {
    printPrimes(100);
}

public static void printPrimes(int range) {
    for (int iCounter=1; iCounter<=range; ++iCounter) {
        if (iCounter <= 1) continue;
        if (iCounter == 2 || iCounter == 3) {
            System.out.println(iCounter);
            continue;
        }
        if (iCounter%2 == 0) continue;
        int iCounterSqrt = (int) Math.sqrt(iCounter);

        boolean bPrime = true;
        for (int iDenom=3; iDenom <= iCounterSqrt; iDenom += 2) {
            if (iCounter % iDenom == 0)
                bPrime = false;
        }

        if (bPrime) {
            System.out.println(iCounter);
        }
    }
}
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package javaapplication4;

/**
 *
 * @author sahadev & vignesh
 */
 class primecollection {


    public static void main(String[] args) {
     int r,s=0,k=0;
      int i,j;
      int a[] = new int[50];
      for(i=2;k<10;i++)
      {
        for(j=1;j<=i;j++)
        {
         r = i%j;

         if(r==0)
         {
          s++;
         }
         if(s==2)
         {
           a[k] = i; 
           k++;
         }
        }
        System.out.println(a[k]);
    }

}
}

If you are testing this with large numbers, using SQRT would be more efficient.如果您使用大量数据进行测试,则使用 SQRT 会更有效。 http://www.wikihow.com/Check-if-a-Number-Is-Prime http://www.wikihow.com/Check-if-a-Number-Is-Prime

    Scanner reader = new Scanner(System.in);
    System.out.println("Enter the a number");
    int num = reader.nextInt();
    int counter = 0;
    int root = 0;
    boolean prime_flag;

    if (2 <= num) {
        // 2 is the only even prime number
        counter++;
    }

    for (int i = 3; i < (num + 1); i++) {

        // test only for odd number
        if (i % 2 != 0) {
            prime_flag = true;
            root = (int) (Math.sqrt(i) + 1);

            for (int j = 3; j < (root + 1); j++) {
                if ((i % j == 0) && (i != j)) {

                    prime_flag = false;
                    break;
                }
            }

            if (prime_flag) {
                counter++;
            }

        }

    }

    System.out.println("Count of prime numbers upto " + num + " is "
            + counter);

Here is the code for getting prime numbers till 'n' in Javascript.这是在 Javascript 中获取素数直到 'n' 的代码。 It is a optimized code and you can refactor your code accordingly.它是经过优化的代码,您可以相应地重构您的代码。 Basic logic: For every number i check if it is divisible by any prime number we have already found till it is less than or equal to i/2.基本逻辑:对于每个数字,我检查它是否可以被我们已经找到的任何素数整除,直到它小于或等于 i/2。

function getPrimesTill(n){
  var i, j, len, limit, result = [];
  for(i=2;i<n;i++){
      limit = i/2;
      len = result.length;
      isPrime = true;
      for(j=0;len && result[j]<=limit;j++){
          if(i%result[j] == 0){
              isPrime = false;
              break;
          }
      }
      if(isPrime) result.push(i);
  }
  return result;
}
getPrimesTill(100);

You can reduce the time it takes the computer to find the prime numbers by following these steps!通过以下步骤,您可以减少计算机查找素数所需的时间!

  • You only have to check if the new number is divisible by before primes您只需要检查新数字是否可以被前素数整除
  • You only have to do this up to the square root of the examined number您只需要计算所检查数字的平方根
  • You only have to check a number if it is a just number你只需要检查一个数字,如果它是一个公正的数字

So I'd do this:所以我会这样做:

public static void searchPrimes() {

    List<Long> primes = new ArrayList<Long>();

    System.out.println(2);

    loop:
    for(long x = 3; x < 100; x += 2) {

        int y = 0;

        while(primes.get(y) < Math.sqrt(x)) {

            if(x % primes.get(y) == 0) {

                continue loop;
            }

            y++;
        }

        primes.add(x);
        System.out.println(x);
    }
}

That's the cleanest and fastest way I found!这是我找到的最干净,最快的方法!

The simpliest way to n.最简单的方法n。

private static void nPrimeNumber(int n) {
    boolean result = true;
    for (int i = 2; i <= n; i++) {
        result = true;
        for (int j = 2; j < i; j++) {
            if (i % j == 0 ) {
                result = false;
                break;
            }
        }
        if(result){
            System.out.print(i+" ");
        }
    }
}
public class listPrimes {
public static void main(String[] args) {
    printPrimes(1000);

}

static void printPrimes(int max) 
{

    for(int k=2;k<=max;k++)
    { 
        int counter=0;
        for(int i=1;i<=k;i++)
        {
            if((k%i)==0)
            {
                counter++;
            }
        }
        if(counter==2)
        {
            System.out.println(k+"is prime");
        }
    }
}

} }

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

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