简体   繁体   English

在Java中查找素数

[英]Finding prime numbers in Java

I have got a java code that checks for prime numbers and then it displays them. 我有一个java代码检查素数,然后显示它们。 However, there are some instances when there are no prime numbers (eg between 14 - 17). 但是,有些情况下没有素数(例如14-17之间)。 In those cases I want a single message to appear. 在这些情况下,我想要显示一条消息。 For example "No primes found" . 例如"No primes found" I don't know how to add this to my code. 我不知道如何将其添加到我的代码中。

This is my whole class: 这是我的全班:

import java.io.*;

public class Prime {

    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

    public static int lowerBound;
    public static int higherBound;

    public void getInput() throws IOException {
        System.out.println("Please enter the lower and upper bound");
        String line1 = input.readLine();
        String line2 = input.readLine();
        int lowInput = Integer.parseInt(line1);
        int highInput = Integer.parseInt(line2);
        lowerBound = lowInput;
        higherBound = highInput;
    }

    public void validatedata() throws IOException {
        do {
            getInput();
            if (lowerBound < 2) {
                System.out.println("Finish");
                break;
            } else if (higherBound < lowerBound) {
                System.out
                        .println("The upper bound should be at least as big as the lower bound.");
            }

        } while (higherBound < lowerBound);

    }

    public void prime_calculation() throws IOException {
        while ((lowerBound >= 2) && (higherBound > lowerBound)) {

            int k;
            for (k = lowerBound; k < higherBound; k++) {
                boolean primecheck = true;
                for (int j = 2; j < k; j++) {
                    if (k % j == 0) {
                        primecheck = false;
                    }
                }
                if (primecheck)
                    System.out.println(k);
            }
            validatedata();
        }
    }
}

And this is my main void method: 这是我的主要虚空方法:

import java.io.IOException;

public class PrimeUser extends Prime {

    public static void main(String argv[]) throws IOException {
        Prime isprime = new Prime();
        isprime.validatedata();
        isprime.prime_calculation();
    }
}
ArrayList<Integer> primes = new ArrayList<Integer>();
if ((lowerBound >= 2) && (higherBound > lowerBound))
{
    int k;
    for (k = lowerBound; k < higherBound; k++)
    {
        primecheck = true;
        for (int j=2; j < k/2; j++) // you dont have to check beyond k/2, since (k/2 + 1) times anything whole number cannot be equal to k
        {
            if (k % j == 0) {
                primecheck = false;
                break; // no need for more iterations of the current number, since you already know it is not a prime
            }
        }
        if (primecheck) {
            primes.add(k);
        }
    }
} else {
    // invalid bounds
    return;
}
if (primes.size() > 0) {
    for (int num : primes) {
        System.out.println(num);
    }
} else {
    System.out.println("No primes exist");
}

// Without an array
boolean y = false;
String x = new String();
if ((lowerBound >= 2) && (higherBound > lowerBound))
{
    int k;
    for (k = lowerBound; k < higherBound; k++)
    {
        primecheck = true;
        for (int j=2; j < k/2; j++) // you dont have to check beyond k/2, since (k/2 + 1) times anything whole number cannot be equal to k
        {
            if (k % j == 0) {
                primecheck = false;
                break; // no need for more iterations of the current number, since you already know it is not a prime
            }
        }
        if (primecheck) {
            x += Integer.toString(k) + "\n";
            y = true; // yes, there exists atleast 1 prime
        }
    }
} else {
    // invalid bounds
    return;
}
if (y == true) {
    System.out.println(x);
} else {
    System.out.println("No primes exist");
}

Assumes that 2 and 3 are known primes: Will find 1 million prime numbers in less than 900 milli sec 假设2和3是已知素数:将在不到900毫秒内找到100万个素数

public class FindPrime { private Integer [] arr_num = new Integer[1000000]; public class FindPrime {private Integer [] arr_num = new Integer [1000000];

    private void arr_init()
    {
        for(int i=0; i< arr_num.length; i++)
        {
            arr_num[i] = i;
        }
    }

    private void find_prime()
    {
        for (int i=3; i<arr_num.length; i++)
        {
            find_prm(arr_num[i]);
        }
    }

    private void find_prm(Integer chk_prm)
    {
        boolean isprime = false;
        if(chk_prm == null)
            return;

        if(chk_prm %2 !=0 )
        {
            double sqrt = Math.sqrt(chk_prm);
            for(Integer k=arr_num[2]; (k!= null) && (k<sqrt + 1)  ; k++)
            {
                if(chk_prm % k == 0)
                {
                    isprime=false;
                    break;
                }
                else
                    isprime = true;
            }
        }
        else
        {
            setNull(chk_prm);
        }
        if(!isprime)
        {
            setNull(chk_prm);
        }
    }

    private void setNull(int num_to_null)
    {
        arr_num [num_to_null] = null;
    }

    private void print_prime()
    {
        for(int i=2; i < arr_num.length; i++)
        {
            if(null != arr_num[i])
            {
                System.out.println(arr_num[i]);
            }
        }
    }

    public static void main(String [] args)
    {
        FindPrime findPrime = new FindPrime();
        findPrime.arr_init();
        long timeStart = System.currentTimeMillis();
        findPrime.find_prime();
            long diff = System.currentTimeMillis()- timeStart;
        System.out.println("Running time :: " + diff);
    }
}

Have a look at http://rosettacode.org/wiki/Miller-Rabin_primality_test#Java which explains how to determine whether a number is a prime. 看看http://rosettacode.org/wiki/Miller-Rabin_primality_test#Java ,它解释了如何确定数字是否为素数。

And then work over your array of values and keep a flag whether a number is a prime or not. 然后处理你的数组值并保持一个数字是否是一个素数。

I found an easier way to solve the problem. 我找到了一种解决问题的简便方法。 I simply added a counter to count the occurrences of primes. 我只是添加了一个计数器来计算素数的出现次数。 If the counter equals = 0 then display the message. 如果计数器等于= 0,则显示消息。 The code is below. 代码如下。 Thanks for your help anyway, guys. 不管怎样,谢谢你的帮助。 If I've got any issue I will post again. 如果我有任何问题,我会再次发布。 Btw, I wonder if anyone can tell me or share any source/webpage or simply any way I can train my algorithm skills in finding solutions ? 顺便说一句,我想知道是否有人可以告诉我或分享任何来源/网页,或者只是以任何方式训练我的算法技巧来寻找解决方案?

the final code here 最后的代码在这里

    public void prime_calculation() throws IOException
{   

    while ((lowerBound >= 2) && (higherBound > lowerBound))
    {

        int k;
        int m = 0;
        for (k = lowerBound; k < higherBound; k++)
        {
            boolean primecheck = true;
                for (int j=2; j < k; j++)
                {
                    if (k % j == 0)
                    {
                        primecheck = false;
                    }
                }
                    if (primecheck)
                    {               
                    System.out.println(k);
                    m++;
                    }
        }
        if (m == 0)
            System.out.println("No primes found");
    validatedata();
    }   
}

} }

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

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