Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何将数字相乘直到达到一位数并计数?_Php_Arrays_Foreach_Split - Fatal编程技术网

Php 如何将数字相乘直到达到一位数并计数?

Php 如何将数字相乘直到达到一位数并计数?,php,arrays,foreach,split,Php,Arrays,Foreach,Split,其描述如下: persistence(39) == 3 // because 3*9 = 27, 2*7 = 14, 1*4=4 // and 4 has only one digit persistence(999) == 4 // because 9*9*9 = 729, 7*2*9 = 126, // 1*2*6 = 12, and finally 1*2 = 2 persistence(4) == 0 // because 4 is already a one-digit numbe

其描述如下:

persistence(39) == 3 // because 3*9 = 27, 2*7 = 14, 1*4=4
// and 4 has only one digit

persistence(999) == 4 // because 9*9*9 = 729, 7*2*9 = 126,
// 1*2*6 = 12, and finally 1*2 = 2

persistence(4) == 0 // because 4 is already a one-digit number
我只能这样做:

$array = str_split(39);

    foreach ($array as $key => $value) {
        echo $array[$key]*$array[$key+1];
    }
第二天我很困惑

有什么解决我问题的方法吗?

$array=str_split('999')//你的绳子
$array = str_split('999'); //Your string
$j=0; //Counter for counting the number of iteration
while (count($array)>1){ //When more than 2 indexes in array
 for($i=0;$i<count($array);$i++){ //Iterate through all permutations
     $array = array_product($array); //Multiplies all numbers in array
     $array = str_split($array); //Split the array up again
     $j++; //Increment counter(as literal as I can sound)
 }
}
echo $j; //Print out the number of times
$j=0//用于计算迭代次数的计数器 而(count($array)>1){//当数组中的索引超过2个时
对于($i=0;$i您也可以使用函数调用,直到它只有一个数字

$count = 0;
persistence(2,$count);
function persistence($i,&$c){   
     $v = str_split($i);
        if(count($v) > 1){
            $total = array_product($v);
            $c++;
            persistence($total,$c);
        }
}
var_dump($count);

我喜欢这个问题。除了在
php
标签下重复的无聊问题之外+1@AlBundy是的,我同意了!这是一个很好的机会,可以让我稍微动一下脑筋:)@我不知道如何给你的答案编代码。你的回答对我来说太快了,但我们现在在欧洲早上5点20分,我每天工作16个小时,我的大脑暂时停止工作……我需要你的帮助。看这里:@samueltoh roberto06已经为你提供了一个完美的例子。