i try to get the 1000000th digit from a consecutive number like this: 1234567891011121314151617......
After waiting for a minute, I got 3
, which is the 1,000,000th digit, but when I try to get the 1,000,000,000th digit, I got this message:
[Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 40009728 bytes) in C:\xampp\htdocs\get ew.php on line 4391
This is my code:
<?php
$tot = 1000000000;
$i = 0;
$j = 1;
$a = array();
do{
$length = strlen((string)$j);
$str = str_split((string)$j);
if($length == 1){
if($i == $tot - 1){
$a[$i] = $j;
}
$i++;
$j++;
}
else{
for($o = 1;$o<=$length;$o++){
if($i==$tot){
break;
}
if($i == $tot -1){
$a[$i] = $str[$o - 1];
}
$i++;
}
$j++;
}
}
while($i<$tot);
echo print_r($a);
?>
how can php generate the 1,000,000,000th digit when it cannot generate 1,000,000,000 numbers?
You will have to optimize your algorithm to find the Nth digit of the series 123...9101112.....100101102......
There are then two easy ways to solve this problem:
1/ Run a loop, keep adding digits of each number, lets call it sum , when you add number of digits of next number in loop ,say ndigits , if sum+ndigits is more than the N ( the digit required), you stop, and check for (Nth-sum) digit in current number.
demo : http://codepad.org/Dekq4bCW
<?php
function findDigit($n)
{
$sum = $num = 0;
do{
$num += 1;
$sum += strlen($num);
}while($n > $sum);
$numStr = (string)($num);
$dig = $numStr[$n - ($sum-strlen($numStr)) - 1] ;
echo "Digit at ".$n." is : ".$dig."
";
}
for($i=9;$i<=15;$i++)
{
findDigit($i);
}
?>
2/ Since the pattern of digits is already known i.e. 9 single digits, then double digits, then triple digits etc. You can figure out a generalized formula to give you digit in Nth place in a single call.