program logic of printing the prime numbers

前端 未结 7 573
别那么骄傲
别那么骄傲 2021-01-25 22:15

Can any body help to understand this java program?

It just prints prime numbers, as you enter how many you want and it works well.

class PrimeNumbers
{           


        
7条回答
  •  滥情空心
    2021-01-25 22:34

    A number N is prime if the only integers that satisfy N = A*B are 1 and N (or N and 1).

    Now to check a number N as prime we could search all A from 2 to N and B from 2 to N, to see if N=A*B. That would take O(N^2) time, and is really inefficient.

    It turns out that we only need to divide N by a number and see if there is a remainder. This brings it down to O(N).

    And further, we don't need to check all the way from A=2 to A=N. If A is greater than sqrt(N), then B must be less than sqrt(N). Therefore we only need to check A from 2 to sqrt(N) to see if N/A has a remainder.

提交回复
热议问题