How do I generate Primes Using 6*k +- 1 rule

前端 未结 7 1438
离开以前
离开以前 2021-02-04 02:07

We know that all primes above 3 can be generated using:

6 * k + 1
6 * k - 1

However we all numbers generated from the above formulas are not pr

7条回答
  •  醉梦人生
    2021-02-04 02:54

    This method below shows how to find prime nos using 6k+/-1 logic

    this was written in python 3.6

    def isPrime(n):
        if(n<=1):
            return 0
        elif(n<4):   #2 , 3 are prime
            return 1
        elif(n%2==0):  #already excluded no.2 ,so any no. div. by 2 cant be prime
            return 0
        elif(n<9):   #5, 7 are prime and 6,8 are excl. in the above step
            return 1
        elif(n%3==0):
            return 1
    
        f=5         #Till now we have checked the div. of n with 2,3 which means with 4,6,8 also now that is why f=5
        r=int(n**.5)    #rounding of root n, i.e: floor(sqrt(n))    r*r<=n
        while(f<=r):
            if(n%f==0): #checking if n has any primefactor lessthan sqrt(n), refer LINE 1
                return 0
            if(n%(f+2)==0): #remember her we are not incrementing f, see the 6k+1 rule to understand this while loop steps ,you will see that most values of f are prime
                return 0
            f=f+6
    
        return 1    
    
    def prime_nos():
        counter=2  #we know 2,3 are prime
        print(2)
        print(3)   #we know 2,3 are prime
        i=1
        s=5  #sum  2+3
        t=0
    
        n=int(input("Enter the upper limit( should be > 3: "))
    
        n=(n-1)//6   #finding max. limit(n=6*i+1) upto which I(here n on left hand side) should run
        while(i

提交回复
热议问题