phpInDev

prime_test

int prime_test ( int number )

Attempts to find the lowest divisor for given number. The lowest divisor is always positive, even for negative numbers. If 0 is given, then 0 will be returned, otherwise the lowest divisor above 1 is returned. If the number is prime (i.e. the lowest divisor above one is the number itself) then 1 will be returned.

NOTE: This does not actually test whether given number is prime or not, because primes must be positive, and primes must also be bigger than 1 (the script will also return 1, if 1 is given).

Example 1. Checking if number is prime

{ number = get_integer("Enter number", 0); if (number < 2 || prime_test(number) != 1) { show_message("It's not a prime"); } else { show_message("You've found a prime!"); } }

When entering 7, this would show:

You've found a prime!

Code for prime_test.gml

{
    argument0 = floor(argument0);
    
    if (argument0 == 0)
    {
        return 0;
    }
    if (argument0 mod 2 == 0 && argument0 != 2)
    {
        return 2;
    }
    if (argument0 mod 5 == 0 && argument0 != 5)
    {
        return 5;    
    }
    
    var add, i, lim;
    
    add[1] = 2;
    add[3] = 4;
    add[7] = 2;
    add[9] = 2;
    
    lim = sqrt(argument0);
    for (i = 3; i <= lim; i += add[i mod 10])
    {
        if (argument0 mod i == 0)
        {
            return i;
        }
    }
    
    return 1;
}