如何从大数中找到特定数字并计算它?

How to find a specific digit from large number and count that?

这里我尝试找出所有 2 并从给定的数字中计算它们。 我已经做到了。 但是我的代码适用于少数人,比如 $number=25,但如果 $number=10000000000;则无法回显 $n,我认为是因为执行时间。大量的任何更好的方法?

<?php
$n =0 ;
$number =25;
for($j = 1; $j<=$number ; $j++)
{
$l = strlen($j);
for($i =0;$i<$l;$i++)
{
$d = substr($j,$i,1);

    if($d ==2)
    {
        $n++;
    }

  }
 }
 echo $n;
 // answer is 9

?>

Here i try to find out all 2's and count them from a given number . i already did it. But my code worked for small number like $number=25, but if $number=10000000000;then unable to echo $n ,i think because of execution time . Any better ways for large number??

你描述的应该差不多

<?php

// clunky version with a loop
function countInStr($str, $chr) {
    $n = 0;
    $l = strlen( $str );
    for( $i =0; $i < $l; $i++ ) { 

        if( $chr == substr($str, $i, 1) ) {
            $n++;
        }

    }
    return $n;
}

$number = 25;
$sum=0;
for ( $i=0; $i <= $number ; $i++ ) {
    //echo $i." ";
    $sum += countInStr( $i, '2' );
}
echo $sum." ?= 9";

// x        counted in 1*10^x
/*
$known[6] = 600000; //1000000
$known[5] = 50000;  //100000
$known[4] = 4000;   //10000
$known[3] = 300;    //1000
$known[2] = 20;     //100
$known[1] = 1;      //10
*/

?>
  • 数字类型仅为特定范围定义,因此会限制长度
  • 而不是使用数组(列表)或字符串,那么你的限制就会少得多
  • 不知道这两个循环是干什么用的,但是按照你的描述你只想做一个计数循环;数组答案也符合问题,不知道为什么人们投票给其他试图帮助的人
  • 为示例添加的范围 (0,max) 内的计数数字总和
  • 正如您在列表 $known 中看到的(这适用于计算所有数字,而不仅仅是 2)您可以使用一种算法来更智能地区分更大的数字并替换 "stupid" 计数。看看像 log()pow() 这样的算术函数;提示:这有点像将数字从一种数字系统转换为另一种数字系统

也许这就是您要找的

function count_char_in_string($str,$char){  // This one counts the $char in a single string
    $str="".$str;   // Convert to a string actually
    $total=0;
    for ($ix=0;$ix<strlen($str);$ix++){
        if (substr($str,$ix,1)==$char) {
            $total++;
        }
    }
    return $total;
}

$n=25000;
$total=0;
for ($ix=0;$ix<=$n;$ix++){
     $total+=count_char_in_string($ix,"2");
}
echo $total;

我认为你可以避免使用模数进行字符串转换。

PHP

<?php

$count = 0;
$n = (int) $argv[1];

for ($i = 0; $i <= $n; $i++) {
    $ii = $i;
    while ($ii > 1) {
        if ($ii % 10 == 2) {
            $count++;
        }
        $ii /= 10;
    }
}

echo $count;

如果我 运行 php run.php 1e8 我会得到:

User time (seconds): 117.98
System time (seconds): 1.17
Percent of CPU this job got: 95%
Elapsed (wall clock) time (h:mm:ss or m:ss): 2:05.00

C

为了比较,我使用 C:

编写了相同的脚本
#include <stdio.h>

int main(int argc, char *argv[]) {
    double n;
    sscanf(argv[1], "%lf", &n);
    int count = 0;

    for (int i = 0; i <= n; ++i)
    {
        int ii = i;
        while (ii > 1) {
            if (ii % 10 == 2) {
                count++;
            }
            ii /= 10;
        }
    }

    printf("%d\n", count);

    return 0;
}

使用相同的号码 ./count 1e8 我得到这个:

User time (seconds): 1.21
System time (seconds): 0.00
Percent of CPU this job got: 98%
Elapsed (wall clock) time (h:mm:ss or m:ss): 0:01.24