Home >Backend Development >PHP Tutorial >PHP printing Yang Hui triangle small example

PHP printing Yang Hui triangle small example

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-25 09:13:021569browse

Example, PHP prints Yang Hui triangle.

  1. /**

  2. * Print Yang Hui triangle:
  3. * 1
  4. * 1 1
  5. * 1 2 1
  6. * 1 3 3 1
  7. * 1 4 6 4 1
  8. * 1 5 10 10 5 1
  9. * 1 6 15 20 15 6 1
  10. *
  11. */
  12. function yang_hui_san_jiao($n)
  13. {
  14. $arr=array(1); //$arr records the previous line Element

  15. $return_html='

    '; //Define a variable to record the output html

  16. //The outer loop controls the number of lines

  17. for( $i=1;$i<=$n;$i++)
  18. {
  19. $return_html.='
  20. ';

  21. //The inner loop controls the number of changed elements

  22. for($j=1;$j<=$i;$j++)
  23. {
  24. //The first and last elements of the changed line are always 1
  25. if($j==1 || $j==$i )
  26. {
  27. $new_arr[$j]=1; // Define a new array $new_arr to record the elements of the current row,

  28. $return_html.='

  29. ';
  30. }

  31. $return_html.='

  32. 1';
  33. }
  34. else
  35. {
  36. //Otherwise, this element is equal to the same subscript and subscript-1 of the previous row. The sum of the two elements
  37. $new_number=$arr[$j]+$arr[$j -1];
  38. $new_arr[$j]=$new_number; //Assign elements to the new array

  39. $return_html.='

  40. '.$new_number.'< /td>';
  41. }
  42. }

  43. $arr=$new_arr; //Assign the array of the current row to $arr and start a new cycle

  44. < ;p> $return_html.='
  45. ';

  46. return $return_html;

  47. }

  48. //Call function to test Yang Hui triangle

  49. echo yang_hui_san_jiao(10);
  50. ?>

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