php写杨辉三角算法

时间:2023-03-09 13:34:44
php写杨辉三角算法

<?php
function YangHui($iLine)
{  
    for ($i = 0;$i <= $iLine;$i++)//行  
    {
        for ($j = 0;$j <= $i;$j++)//列  
        {
            if ($i == $j)//行=列(也就是最后一列)或者第一行和第一列  
            {
                $a[$i][$j] = 1;
                if($i==0){

//str_repeat() 函数把字符串重复指定的次数。str_repeat(".",13);输入13个.
                  $str="";
                  $newStr= str_pad($str, ($iLine-$i), ".", STR_PAD_LEFT);
                  $nbsp = str_replace(".","&nbsp;",$newStr);
                }else{
                  $nbsp = "";
                }
                 echo $nbsp.$a[$i][$j]."<br>";
                  
            }
           else if ($i != 0 && $j == 0)//行=列(也就是最后一列)或者第一行和第一列  
            {
                $a[$i][$j] = 1;
                
                $str='';
                $newStr= str_pad($str, ($iLine-$i), ".", STR_PAD_LEFT);
                $nbsp = str_replace(".","&nbsp;",$newStr);
                echo $nbsp.$a[$i][$j]."&nbsp;";
            }
   
            else
            {
               
               $a[$i][$j] = $a[$i-1][$j]+$a[$i-1][$j-1];//行+列的值=上一行2个值相加  
              echo $a[$i][$j]."&nbsp;";
            }
        }
    }
   return $a;
}
 
 YangHui(9);

?>