Page 1 of 1

number types

Posted: Wed Oct 28, 2009 7:06 am
by ozulloa
Hi!
I need help creating a web app that will help me find and list in a table if a number is either even, prime or perfect. It will be like:

Value Even Prime Perfect
370 x x

This will be in a table and will place an x on the type of number entered by the user in a box

Thanks,

Re: number types

Posted: Wed Oct 28, 2009 7:31 am
by Mark Baker
This may help

Code: Select all

 
isEven($number) {
    return (($number % 2) == 0);
}
 
isPrime($number) {
    $No = 0; 
    for ($CurrNum = 2; $CurrNum <= $Num; $CurrNum++) {
        for ($Divisor = 2; $Divisor < $CurrNum; $Divisor++) { 
            $Res = $CurrNum / $Divisor; 
            if ($Res != 1 && intval($Res) == $Res) {
                $No = 1;
                $Divisor = $CurrNum; 
            }
        }
        if ($No != 1) {
            $Result = $CurrNum;
        }
        $No = 0;
    }
 
    // If the only divisor is the number itself, it's prime
    if ($Result == $Num) {
        return True;
    }
    return False; 
}
 
isPerfect($number) {
    // Only positive integers can be perfect.
    if ($number < 1) {
        return False;
    }
    // Calculate the factors for the given number.
    $arrFactors = array();
    for ($i = 1; $i <= $number; $i++) {
        if (($number % $i) == 0) {
            $arrFactors[] = $i;
        }
    }
    // A perfect number is a number that is half the sum of all of its positive divisors (including itself).
    return ($number == array_sum($arrFactors) / 2);
}