سؤال

I have got a java code that checks for prime numbers and then it displays them. However, there are some instances when there are no prime numbers (e.g between 14 - 17). In those cases I want a single message to appear. For example "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();
    }
}
هل كانت مفيدة؟

المحلول 3

Have a look at http://rosettacode.org/wiki/Miller-Rabin_primality_test#Java which explains how to determine whether a number is a prime.

And then work over your array of values and keep a flag whether a number is a prime or not.

نصائح أخرى

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

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

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. 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 مع الإسناد
لا تنتمي إلى StackOverflow
scroll top