Prime Number Generator Logic

后端 未结 15 2321
旧时难觅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:43

    I think there could be a faster solution for that....

    We all know that 2 is the first prime number,and a prime number is one which is just divisible by 1 and itself.

    Let N = number entered by user till where we have to print the prime. Now,

    if(N<2)
    // No prime numbers
    
    if(N==2)
    // Print 2
    
    if(N>2)
    //print 2
     Create a list(or any resize able data structure)   and add 2 to it.
     now,
     run a loop from i= 3 to i<=n
    {
             count how many numbers in the list are able to divide i completely(Let c                   
    denotes it)
      if(c==0)
    //print the number as it is prime
     }
    

提交回复
热议问题