0

I know this is a very repetitive question on here, but I was looking to understand if I could simply check for a big integer, (eg. 157,632,829) by check if its divisible by 2, 3, 5 or 7, or am I missing corner cases?

ie.

if (n < 4) :
        return True
if (n % 2 == 0 or n % 3 == 0 or n % 5 == 0 or n % 7 == 0) :
        return False
TheKingSid
  • 39
  • 6

2 Answers2

0

If you don't mind a looped approach then you could try this. Runs in 6ms on my machine:

import math
import time

def gen_prime():
    D = {}
    q = 2
    while True:
        if q not in D:
            yield q
            D[q * q] = [q]
        else:
            for p in D[q]:
                D.setdefault(p + q, []).append(p)
            del D[q]
        q += 1


def isprime(n):
    if n >= 2:
        g = gen_prime()
        s = int(math.sqrt(n))
        while True:
            d = next(g)
            if d > s:
                return True
            if n % d == 0:
                break
    return False

s = time.perf_counter()
r = isprime(157_632_829)
e = time.perf_counter()
print(f'{r} {e-s:.4f}s')

Note: The gen_prime() generator is not mine. Unfortunately I can't remember where I got it from so can't give credit

0

A very simple routine would be

bool isprime( int n )
{
   for( int i = 2; i < n; i++ ) if( n % i == 0 ) return false;
   return true;
}

There are lots of ways to optimize it.

brian beuning
  • 2,836
  • 18
  • 22