Home >Backend Development >PHP Tutorial >Used for simple algorithm attempts

Used for simple algorithm attempts

WBOY
WBOYOriginal
2016-07-25 09:01:10900browse
If the sum of all factors of a positive integer greater than 1 is equal to itself, the number is called a perfect number. For example, 6 and 28 are both perfect numbers: 6=1+2+3; 28=1+2+4+ 7+14.
  1. //Judge whether it is a complete number
  2. function is_factor($factor)
  3. {
  4. if($factor<1) return false;
  5. if($factor==1) return array(1);
  6. if(! isset($arr)){$arr=array();}
  7. for($i=1;$i<$factor;$i++){
  8. if($factor%$i==0){
  9. $arr[ ]=$i;
  10. }
  11. }
  12. $len=count($arr);
  13. $i=0;$temp=0;
  14. while($i<$len) {$temp+=$arr[$i]; $i++;}
  15. if($temp==$factor) return $arr;
  16. else return false;
  17. }
  18. $factor=6;
  19. $count=0;
  20. for($i=1;$i<= $factor;$i++)
  21. {
  22. $res=is_factor($i);
  23. $len=count($res);
  24. if(is_array($res)){
  25. echo $i.'=';
  26. for( $j=0;$j<$len;$j++){
  27. if($j!=0) echo '+'.$res[$j];
  28. else echo $res[$j];
  29. }
  30. $ count++;
  31. echo '
    ';
  32. }
  33. }
  34. if($count==0) echo 'No complete number!';
Copy code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn