Prime Number Generator Logic

后端 未结 15 2226
旧时难觅i
旧时难觅i 2021-01-07 04:10

I am supposed to make a class PrimeNumberGenerator which has a method nextPrime that will print out all prime numbers up to a number the user input

相关标签:
15条回答
  • 2021-01-07 04:53

    I use this way in generator, it works well.

    const isPrime = (number) => {
      if (
        Number.isNaN(number) ||
        !Number.isFinite(number) ||
        number % 1 || //  check int number
        number < 2
      ) {
        return false;
      }
      let i = 2;
      const m = Math.ceil(Math.sqrt(number));
      let isPrime = true;
      while (i <= m) {
        if (number % i === 0) {
          isPrime = false;
          break;
        }
        i = i + 1;
      }
      return isPrime;
    };
    
    function* primeNumber() {
      let nextNumber = 2;
      while (true) {
        if (isPrime(nextNumber)) {
          yield nextNumber;
        }
        ++nextNumber;
      }
    }
    
    const iter = primeNumber();
    for (const n of iter) {
      if (n > 100) iter.return("end");//end loop
      console.log(n);
    }
    

    You can call next to get prime number in order.

    const iter = primeNumber();
    console.log(iter.next())
    console.log(iter.next())
    

    include thoes function to your class.

    0 讨论(0)
  • 2021-01-07 04:55

    Simple definition of a prime number: A number that is only divisible by one and by itself. By definition 1 isn't prime. Here is a brute force algorithm to determine if a number is prime or not.

        boolean isPrime(int n)
        {
            for (int i = 2; i < n; i++)
                if (n % i == 0)
                    return false;
            return true;
        }
    
    0 讨论(0)
  • 2021-01-07 04:57

    There are two questions here that you have forgotten to ask:

    • Why does the nested loop make everything so complicated?
    • What can I do to uncomplicate things again?

    So let's play along with the question you actually asked, and then answer the first two questions.

    What you want to do can probably be described as such: For every number, 1-n, where n is input by the user, print it if it's prime.

    Okay, so let's write up the pseudocode/logic here. It looks like Java, but it isn't. It's just meant to convey what we're going for:

    int largestNumber = readIntegerFromKeyboard();
    
    for all ints i from 1 to largestNumber {
        if(isPrime(i)) {
            println(i);
        }
    }
    

    So let's do this! But first, we need a laundry-list of all the things we need to do:

    • read integer from keyboard
    • loop over numbers
    • check if the number is a prime
    • print primes (with newlines)

    Let's just do the two easy things first. Reading the input and setting up the loop:

    Scanner keyboard = new Scanner(System.in);
    int largestNumber = keyboard.nextInt();
    
    for(int i = 1; i <= largestNumber; ++i) {
        if(isPrime(i)) {
            System.out.println(i);
        }
    }    
    
    keyboard.close();
    

    Okay, that seems simple enough. So far, everything here makes sense. It's easy to understand the logic. Now however, when we replace isPrime with actual logic, everything is about to get cluttered and hard to read.

    So let's write this code as easy to understand as possible. We will use no tricks to speed up the code. Readability and correctness are the only two things we will care about. We will use the modulo operator to check if something is evenly dividable. Modulo is like integer division, except that it returns the remainder and not the result. so 7 / 2 = 2. 7 % 2 = 1, because there's one left over.

    Scanner keyboard = new Scanner(System.in);
    int largestNumber = keyboard.nextInt();
    
    for(int i = 1; i <= largestNumber; ++i) {
        // checks if the number is a prime or not
        boolean isPrime = true;
        for(int check = 2; check < i; ++check) {
            if(i % check == 0) {
                isPrime = false;
            }
        }
        if(isPrime) {
            System.out.println(i);
        }
    }    
    

    So the good news is, this works. The bad news is, this is harder to read than necessary. And it's not a lot we can do here. When I wrote this up, I made several stupid mistakes, mixing up the variables. Maybe I'm stupid. So maybe I should in that case write stupid-proof code. ;) You on the other hand is not stupid. But you may work with me, who is stupid, so you kind of have to write stupid-proof code yourself, so that you can productively work with me.

    The big problem is that we have this massive loop in the middle of the other loop. This is what tripped me up. I referred to the wrong loop variable. But why do we need a loop in a loop? Wasn't it much more comfortable to read:

    if(isPrime(i)) {
        System.out.println(i);
    }
    

    Instead of that whole mess? Your professor pointed out the nested loops. But it threw you off. Instead, just write the isPrime method. And the fact is, that this is true for every single instance of nested loops I have ever come across.. So let's see how that would look instead:

    class Homework {
        public static void main(String[] args) {
            Scanner keyboard = new Scanner(System.in);
            int largestNumber = keyboard.nextInt();
    
            for(int i = 1; i <= largestNumber; ++i) {
                if(isPrime(i)) {
                    System.out.println(i);
                }
            }
            keyboard.close();
        }
    
        /**
         * Checks is a positive integer is a prime number
         */
        public static boolean isPrime(int number) {
            for(int check = 2; check < number; ++check) {
                if(number % check == 0) {
                    return false;
                }
            }
            return true;
        }
    }
    

    That to me is a whole lot easier to read. Not because the logic got easier, but because the only thing I had to care about was either:

    • Checking all the numbers and printing the correct ones, or
    • how to check that a number is a prime.

    Since these two separate things are now apart, you have much less to think about at once. Rejoice, for you have just done a proper abstraction. This makes your code easier to understand, because it separates out the two concerns. This is a key way of making larger projects. You take difficult things and do them by themselves. Then you can test them by themselves, and use them by themselves.

    (Now I only have to await the downvotes for answering a question you didn't explicitly ask...)

    0 讨论(0)
  • 2021-01-07 04:58

    Check this algorithm based on the sieve of Eratosthenes for prime numbers. Of course you need to adapt it to your program.

    boolean isPrime[] = new boolean [N+1];
    for (int i=2; i <=N; i++)
        isPrime[i] = true;
    
    //mark non-primes <=N using Sieve of Eratosthenes
    for (int i=2; i*i<=N; i++) 
    {
        //if is a prime,then mark multiples of i as non prime 
        for (int j=i; i*j<=N; j++) 
        {
            isPrime[i*j] = false;
        }
    }
    
    for (int i=2; i<=N; i++) 
        if (isPrime[i])
            //Do something.......   
    
    0 讨论(0)
  • 2021-01-07 04:59

    I wrote this function which lists the first n prime numbers:

    static void primes(int n) {
        int[] prime = new int[n];
        prime[0] = 2;
        int pp = 0;
    
        int i = 2;
        while(pp < n - 1) {
            int g = 1;
            for(int p = 0; p <= pp; p++) {
                if(i % prime[p] == 0) {
                    g = prime[p];
                    break;
                }
            }
            if(g == 1) {
                pp += 1;
                prime[pp] = i;
            }
            i += 1;
        }
        
        for(int z = 0; z < n; z++) {
            System.out.println(prime[z]);
        }
    }
    

    It also should be relatively fast because it checks the lowest amount of divsors necessary. (i think)

    0 讨论(0)
  • 2021-01-07 05:00
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    import javax.xml.soap.Node;
    
    public class mainone {
    
     public static void main(String args[]){
    
        int[] primenumber=new int[13];
    
        for(int a=2,j=0;a<=14;a++,j++){
            primenumber[j]=a;
    
        }
    
        for(int b=1;b<13;b++){
            int d=primenumber[b];
            if(d%2==0){
                primenumber[b]=0;
            }
    
            for(int c=2;c<13;c++){
                int e=primenumber[c];
                if(e>0){
                    for(int f=c+1;f<13;f++){
                        int g=primenumber[f];
                        if((g>0)&(g%e==0)){
                            primenumber[f]=0;
                        }
    
    
                    }
                }
            }
        }
    
    
        for(int j=0;j<13;j++){
            System.out.println(primenumber[j]);
        }
         }
    
     }
    
    0 讨论(0)
提交回复
热议问题