PHP print Yang Hui triangle small example

Source: Internet
Author: User

Example, php print 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 record the elements of the previous row

  15. $return _html= '

  16. //Outer loop control lines

  17. //Inner loop control number of row elements

  18. }
  19. }
  20. }

  21. for ($i =1; $i <= $n; $i + +)
  22. {
  23. $ return_html.= '
  24. for ($j =1; $j <= $i; $j + +)
  25. {
  26. //The first and last element of a row is always 1
  27. if ($j ==1 | | $j = = $i)
  28. {
  29. $new _arr[$j]=1 ; Defines a new array $new_arr, records the elements of the current row,

  30. $return _html.= '

  31. Else
  32. {
  33. ///Otherwise, the element is equal to the same angle and angle label on the previous line-12 elements and
  34. $new _number= $arr [$j]+ $arr [$j-1];
  35. $new _arr[$j]= $new _number;//assigning elements to a new array

  36. $return _html.= '

  37. }

  38. $arr = $new _arr;//Assign an array of current rows to $arr and start a new round of loops

  39. $return _html.= '

  40. $return _html.= '

  41. ';//define a variable, record the output of HTML '; '; '; ';
    1'. $new _number. '
    ';

  42. return $return _html;

  43. }

  44. Call function test Yang Hui triangle

  45. Echo Yang_hui_san_jiao (10);
  46. ?>

Copy Code
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.