primality test speed

108 Views Asked by At

Noticed using a lattice with line $x+y=n$ for n prime, every grid point on the line is co-prime. For example:

Lattice with x+y=n

To test, I wrote a C program to specify a number (e.g., 104729) then travels along the line looking for a non co-prime point (x,y) and outputs prime or not prime:

#include "stdafx.h"

unsigned int gcd(unsigned int a, unsigned int b) {
    unsigned int t;
    while (b != 0) {
        t = a;       
        a = b;       
        b = t % b;    
    }
    return a;
}

int main(int argc, char *argv)
{
    // x+y=n
    unsigned int x, y, n;

    // This number is prime:
    n = 104729;

    for (x = 1; x < n; x++)
    {
        y = n - x;
        if (gcd(x, y) != 1)
        {
            printf("Not Prime: %u\n", n);
            break;
        }
    }

    if (x == n)
    {
        printf("Prime: %u\n", n);
    }

    return 0;
}

I'm wondering if it's possible to speed up the prime check using some fancy maths tricks.

Thanks.