Home  >  Article  >  Backend Development  >  PHP implementation of narcissus number code sharing

PHP implementation of narcissus number code sharing

WBOY
WBOYOriginal
2016-07-25 09:12:511801browse

The so-called narcissus number is a number raised to a power, also known as Armstrong number. It is also known as narcissus number among the people. In fact, only 3-digit exponentiates are narcissus numbers. 4 digits, 5 digits, 6 digits, etc. have different names.

Example, PHP code to implement narcissus number.

  1. //Armstrong number: a k-digit number, the sum of the k-th power of the numbers in each digit is equal to itself. (Example: 1^3 + 5^3 + 3^3 = 153)
  2. class Armstrong {
  3. static function index(){
  4. for ( $i = 100; $i < 100000; $i++ ) {
  5. echo self: :is_armstrong($i) ? $i . '
    ' : '';
  6. }
  7. } // edit by bbs.it-home.org
  8. static function is_armstrong($num){
  9. $s = 0;
  10. $k = strlen($num);
  11. $d = str_split($num);
  12. foreach ($d as $r) {
  13. $s += bcpow($r, $k);
  14. }
  15. return $num == $s;
  16. }
  17. }
  18. Armstrong::index();
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