Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,907 questions

51,839 answers

573 users

How to check whether number is perfect or not in PHP

2 Answers

0 votes
// If the sum of all factors of a number is equal to the number, then the number is perfect

// Factors of a number are numbers that divide the number evenly

function isPerfectNumber($n) {
    $i = 1;
    $sum = 0;
     
    while ($i < $n)
    {
        if ($n % $i == 0)
        {
            $sum = $sum + $i;
        }
        $i++;
    }
    return $sum == $n;
}

$n = 496;
 
if (isPerfectNumber($n))
    echo $n . " is a Perfect Number";
else
    echo $n . " is Not a Perfect Number";

    
/*
run:

496 is a Perfect Number 
     
*/

 



answered Feb 27, 2016 by avibootz
edited May 18, 2022 by avibootz
0 votes
// If the sum of all factors of a number is equal to the number, then the number is perfect

// Factors of a number are numbers that divide the number evenly

function isPerfectNumber($number) {
    $sum = 0;
    for ($i = 2; $i <= sqrt($number); $i++)
    {
        if (!($number % $i))
        {
            $sum += $i;
            if ($i <> $number / $i)
                $sum += $number / $i;
        }
    }
    return ++$sum == $number;
}

$n = 496;
  
if (isPerfectNumber($n))
    echo $n . " is a Perfect Number";
else
    echo $n . " is Not a Perfect Number";    

 
/*
run: 
  
496 is a Perfect Number
  
*/ 

 



answered Sep 4, 2017 by avibootz
edited May 18, 2022 by avibootz

Related questions

1 answer 104 views
1 answer 111 views
1 answer 107 views
1 answer 99 views
...