簡體   English   中英

在Java中查找素數

[英]Finding prime numbers in Java

我有一個java代碼檢查素數,然后顯示它們。 但是,有些情況下沒有素數(例如14-17之間)。 在這些情況下,我想要顯示一條消息。 例如"No primes found" 我不知道如何將其添加到我的代碼中。

這是我的全班:

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

這是我的主要虛空方法:

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

假設2和3是已知素數:將在不到900毫秒內找到100萬個素數

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

看看http://rosettacode.org/wiki/Miller-Rabin_primality_test#Java ,它解釋了如何確定數字是否為素數。

然后處理你的數組值並保持一個數字是否是一個素數。

我找到了一種解決問題的簡便方法。 我只是添加了一個計數器來計算素數的出現次數。 如果計數器等於= 0,則顯示消息。 代碼如下。 不管怎樣,謝謝你的幫助。 如果我有任何問題,我會再次發布。 順便說一句,我想知道是否有人可以告訴我或分享任何來源/網頁,或者只是以任何方式訓練我的算法技巧來尋找解決方案?

最后的代碼在這里

    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