简体   繁体   中英

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. 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. So after the program is done I'll have a list of prime numbers between 1- 100.

1. Is my program correct for what I'm trying to do? 2. What would be good suggesting to change my program so that it lists all the prime numbers between 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.

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). (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:

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 . 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 . If true, print the number and break out of the loop.

    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. 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. 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.

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
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. The first prime numbers are: 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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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