简体   繁体   English

编写查找素数的方法

[英]Writing a method to find prime numbers

I'm trying to write a program that uses a predicate method that finds all the prime numbers between 1-100. 我正在尝试编写一个程序,该程序使用谓词方法来查找1-100之间的所有素数。 I know there are more efficient ways of finding prime numbers but right now but I want to use the brute-force strategy and try every possible combination. 我知道找到质数有更有效的方法,但是现在,但是我想使用蛮力策略并尝试所有可能的组合。

Right now the program as it is, just prints true or false 10,000 times but I want my program to only print the numbers if they are prime. 现在,该程序原样只打印10,000次对或错,但是我希望我的程序只打印素数的数字。 So after the program is done I'll have a list of prime numbers between 1- 100. 因此,程序完成后,我将得到一个介于1至100之间的质数列表。

1. Is my program correct for what I'm trying to do? 1.我的程序对我要执行的操作是否正确? 2. What would be good suggesting to change my program so that it lists all the prime numbers between 1-100. 2.建议更改我的程序,以便它列出1至100之间的所有素数。

import acm.program.*;
public class PrimeNumbers extends ConsoleProgram{
public void run(){

    for (int i =1; i <= 100, i++){
        for (int j =1; j<= 100; j++){
           println(yesPrime(i, j));
       }
     }
   }

private boolean yesPrime (int n, int k){
      return ( n % k == 0)

       }
    }
  }

You're not checking for primes. 您没有检查素数。 You're testing all 10,000 combinations of two numbers from 1 to 100 to see if the second divides the first evenly. 您正在测试从10,000到10,000的两个数字的所有组合,以查看第二个数字是否均等地除以第一个数字。

But it's likely doing that correctly. 但这可能正确地做到了。

Pseudocode for what you want to do: 您想要做什么的伪代码:

for each number n from 2:100
    for each divisor d from 2:n-1
        test to see if d divided n evenly
    end for
    if no values of d other than n divided n evenly
        print "n is prime"
end for

A couple of optimizations for you to ponder: 有几个优化方案可供您考虑:

  • Your inner loop only has to go up to sqrt(n). 您的内部循环仅需上升到sqrt(n)。 (Why?) (为什么?)
  • Instead of all numbers, you only need to check to see if it divides the odd primes you've already found evenly. 除了所有数字,您只需要检查它是否能将已经找到的奇数素数相除即可。 (Why?) (为什么?)

Have fun! 玩得开心!

Using the sieve of Eratosthenes: 使用Eratosthenes筛子:

public static void main(String[] args) {

    int n = 100; // the max number for test

    // Sieve of Eratosthenes
    boolean[] sieve = new boolean[n + 1];
    for (int i = 2; i <= n; i++) {
        sieve[i] = true;
    }
    for (int i = 2; i <= n; i++) {
        if (sieve[i] != false) {
            for (int j = i; j * i <= n; j++) {
                sieve[i * j] = false;
            }
        }
    }

    // Print prime numbers
    for (int i = 0; i <= n; i++) {
        if (sieve[i]) {
            System.out.println(i);
        }
    }

}

Well, you are returning a comparison from yesPrime , and then printing the result of that comparison in run . 好吧,您要从yesPrime返回比较结果,然后在run打印该比较结果。 Guess what the output would be. 猜猜输出是什么。

Taking that this is an assignment, I would like to give you a hint instead of the answer. 考虑到这是一项任务,我想给你一个提示而不是答案。

Check the result of yesPrime . 检查yesPrime的结果。 If true, print the number and break out of the loop. 如果为true,则打印数字并退出循环。

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

I would make a function, something like your yesPrime function. 我将创建一个函数,类似于您的yesPrime函数。 This would take one number only, and check to see if that number is prime. 这仅需要一个数字,并检查该数字是否为质数。

Something like 就像是

boolean yesPrime(int n)
{
    // check to see if n is divisble by numbers between 2 and sqrt(n)
    // if the number is divisible, it is not prime, so return false
    // after the loop has checked all numbers up to sqrt(n), n must be prime so return true
}

Then in your main program, loop over the numbers 1 to 100 and call yesPrime for each number. 然后在主程序中,将数字1循环到100,并为每个数字调用yesPrime。 If the result is true, print that number. 如果结果为真,则打印该号码。

My reaoning is that one goal of programming is to break problems up into smaller sub-problems. 我的理解是编程的一个目标是将问题分解为较小的子问题。 By writing a function to test for prime, you can avoid using nested loops in one function which could be harder to understand. 通过编写用于测试质数的函数,可以避免在一个函数中使用嵌套循环,而这可能很难理解。

For starters, you need to check for prime numbers starting from 2. And you do not check it against all the 100 numbers, just every number as a factor starting from 2 till (number-1).Every number is divisible by 1 and itself. 对于初学者,您需要检查从2开始的质数。不要对所有100个数字进行质数检查,仅将每个数字作为从2到(number-1)的因子进行检查。每个数字都可以被1整除。

public static void main(String[] args) {
    boolean b;
    for (int i = 2; i < 100; i++) {
        b = checkPrime(i);
        if (b)
            System.out.println(i);
    }
}

private static boolean checkPrime(int k) {

    for (int i = 2; i < k; i++) {  
//check if the number is divisible by any number starting from 2 till number -1.If it is, it is not a prime number
        if (k % i == 0)
            return false;
    }
// return true if the number is not divisible by any number from 2 to number -1 i.e.  it s a prime number.
    return true;
}

Just think about this logic 想想这个逻辑
All number divisible by 2 is not prime so you can increment your number by 2 所有可被2整除的数字不是素数,因此您可以将数字加2
if a number is not divisible by a prime number then it is a prime number 如果一个数字不能被质数整除,那么它就是质数

try this code 试试这个代码

public static void main(String[] args) throws IOException
    {
        int[] prime=new int[50];   //array to store prime numbers| within 1 to ==> prime numbers will be <=n/2 here n=100
        int i=1;        //index for "num" array
        int j=1;        //index for storing to "prime" array
        int k=1;        //index for browsing through prime array
        prime[0]=2;     // setting the first element
        int flag=1;     // to check if a number is divisibe for than 2 times
        for(i=3;i<=100;i+=2) {
            for(k=0;prime[k]!=0;k++)    //browsing through the array to till non zero number is encountered
            {
                if(i%prime[k]==0) flag++;   //checking if the number is divisible, if so the flag is incremented 
            }
            if(flag<2)
            {
                prime[j++]=i;               // if the flag is still 1 then the number is a prime number
            }
            flag=1;
        }
        System.out.println(Arrays.toString(prime)); //a short way to print an array
        }

find prime numbers easy in a given range /* Please implement this method to return a list of all prime numbers in the given range (inclusively). 查找给定范围内的质数很容易/ *请实现此方法以返回给定范围(含)内所有质数的列表。 A prime number is a natural number that has exactly two distinct natural number divisors, which are 1 and the prime number itself. 质数是一个自然数,正好具有两个不同的自然数除数,即1和素数本身。 The first prime numbers are: 2, 3, 5, 7, 11, 13 */ 第一个质数是:2、3、5、7、11、13 * /

public void getPrimeNumbers(int st, int en){
    // int st=1, en=100;
    for(int i=st;i<=en;i++)
        if( (i%2!=0) && (i%1==0 && i%i==0) )
            System.out.println("Yes prime");      
}
public static void main(String[] args) {

    boolean isPrime = true;             //set isPrime to true

    for (int i = 2; i<100;i++){          // consider i is increasing number

        for (int j=2; j<i; j++)           //j is divisor & must be less than
                                         //i and increasing after each iteration
        {
            if((i % j)== 0){             // if i gets divisible by 
                                         // any increasing value of j from 2
                                        //then enters in this case and makes value
                                        //nonPrime
                isPrime=false;     //changes value
            break;                   //breaks "for loop of j"
        }
            }               //ends "for loop of j"
        if(isPrime)            // if case wont work then number is prime
        {

            System.out.println(i + " is Prime");
        }
        isPrime = true;       //sets isPrime to default true. 
    }
    }

With a less complex method we can do this: 使用不太复杂的方法,我们可以执行以下操作:

import java.math.BigInteger;

public class PrimeNumbers {

    public static void main(String[] args) {
        BigInteger min = new BigInteger("2");
        BigInteger max = new BigInteger("100");

        while(min.compareTo(max) < 0){

            System.out.println(min);
            min = min.nextProbablePrime();

        }

    }
}

Here is my solution for finding primes numbers. 这是我寻找素数的解决方案。

public class PrimeNumberFinder {

    public boolean isPrime(int number) {
        return number > 1 && IntStream.rangeClosed(2, number / 2)
                .noneMatch(value -> number % value == 0);
    }
}

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

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