Ken-Soft

Software and the World

Is Prime Number Algorithm

Posted under C/C++, Mathematics, Programming by Kenny on Monday 12 July 2010 at 11:03 am
Bookmark and Share

I was randomly surfing around the internet when I stumbled upon Google Labs Aptitude Test (GLAT)(Found here). I can’t really remember which links I followed from there but I stumbled into a question that asks to find the first 10 consecutive digits of E that are prime. While definitely not a hard task I wrote a small program in C to test whether or not a number is prime.

The core function isPrime() is below

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
long long isPrime(long double n) {
    // is n an integer ?
    if(n / (long long) n != 1.0) {
        return -1;
    }
    // is n even? (half of the numbers)
    if((long long)n % 2 == 0) {
        if(n == 2) {
               return 0;
        }
        return 2;
    }
    long long root = sqrtl(n);
    // is the number divisible by n, such that n > 2 and n <= sqrt(number)?
    // if so then the number is composite
    for(long long i = 3; i <= root; i++) {
        if((long long) n % i == 0) {
            return i;
        }
    }
    return 0; // it is prime!
}

note: I use long long just to allow the calculation of bigger numbers. Though if the number gets to large enough this algorithm can still slow down a bit, as it could potentially have to iterate from 3 to the square root of the number being tested. For most cases this algorithm executes plenty fast enough and it is definitely better than iterating over every number between 1 and N, as many sites do.
the entire implementation is here:main.cpp


No Comments »

RSS feed for comments on this post. TrackBack URI

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Copyright © 2009 www.Ken-Soft.com