Project Euler #58: Spiral primes

  • + 0 comments

    Python

    import random
    
    def isPrimeMillerRabin(n, k=3):
        if n <= 1:
            return False
        if n == 2 or n == 3:
            return True
        if n % 2 == 0:
            return False
    
        r, d = 0, n - 1
        while d % 2 == 0:
            r += 1
            d //= 2
    
        # Perform Miller-Rabin test k times
        for _ in range(k):
            a = random.randint(2, n - 2)
            x = pow(a, d, n)
    
            if x == 1 or x == n - 1:
                continue
    
            for _ in range(r - 1):
                x = pow(x, 2, n)
                if x == n - 1:
                    break
            else:
                return False  
    
        return True  # Likely to be prime
    
    
    N = float(input()) / 100
    count = 0
    i = 3  
    spiral_size = 1
    
    while True:
        for j in range(4):
            num = i**2 - (i - 1) * j
            if isPrimeMillerRabin(num):
                count += 1
                
        spiral_size += 4
        proportion = count / spiral_size
    
        if proportion < N:
            break
    
        i += 2  
    
    print(i)