Example, PHP prints Yang Hui triangle.
-
-
/** - * Print Yang Hui triangle:
- * 1
- * 1 1
- * 1 2 1
- * 1 3 3 1
- * 1 4 6 4 1
- * 1 5 10 10 5 1
- * 1 6 15 20 15 6 1
- *
- */
- function yang_hui_san_jiao($n)
- {
- $arr=array(1); //$arr records the previous line Element
$return_html=' '; //Define a variable to record the output html
//The outer loop controls the number of lines
- for( $i=1;$i<=$n;$i++)
- {
- $return_html.='
';
//The inner loop controls the number of changed elements
- for($j=1;$j<=$i;$j++)
- {
- //The first and last elements of the changed line are always 1
- if($j==1 || $j==$i )
- {
- $new_arr[$j]=1; // Define a new array $new_arr to record the elements of the current row,
$return_html.=' 1 td>';
- }
- else
- {
- //Otherwise, this element is equal to the same subscript and subscript-1 of the previous row. The sum of the two elements
- $new_number=$arr[$j]+$arr[$j -1];
- $new_arr[$j]=$new_number; //Assign elements to the new array
$return_html.=' '.$new_number.'< /td>';
- }
- }
$arr=$new_arr; //Assign the array of the current row to $arr and start a new cycle
- < ;p> $return_html.='
| | ';
- }
$return_html.=' ';
return $return_html;
- }
//Call function to test Yang Hui triangle
- echo yang_hui_san_jiao(10);
- ?>
-
Copy code
|