Optimized prime num method

By BrAndo on Nov 01, 2009

used to tell if a number is prime

you should find it a bit faster than your normal prime number algorithm

i'm not sure which compilers don't accept inline assembly, but i compiled in visual studio.

#include <cmath>

bool prime(unsigned n)
    switch (n)
        case 0:
        case 1:
            return false;
        case 2:
        case 3:
            return true;

    double dSq = sqrt((double)n);
    unsigned sqrt = (int)dSq;

    unsigned prime;
    // check 2 to sqrt for divisibility
        mov esi, n    
        mov edi, sqrt

        mov ebx, 1  
        mov ecx, 1   
        inc ecx       
        cmp ecx, edi   
        ja _end       
        mov eax, esi
        xor edx, edx
        div ecx
        cmp edx, 0 
        jne _loop
        mov ebx, 0

        mov prime, ebx
    return (prime == 1);


Sign in to comment.
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.