note 72265 deleted from function.is-numeric by nlopess
| From: | nlopess@php.net | Date: | Wed, 10 Jan 2007 14:53:06 +0000 |
| Subject: | note 72265 deleted from function.is-numeric by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-121530@lists.php.net to get a copy of this message | ||
Note Submitter: sneskid at hotmail dot com
Reason: useless
----
This is a simple sum-of-numbers non-recursive function.
I did not see it anywhere else on the site and this seems like a good spot.
It was created in response to:
http://www.10-minute-rule.com/index.php?itemid=116
<?php
function son($n,$d) {
$n = strval($n);
while(strlen($n) > $d) {
$sum = 0;
$len = strlen($n);
for($i=0;$i<$len;$i++) $sum += $n[$i];
$n = strval($sum);
}
return $n;
}
?>
The function will stop if the length of $n is equal to or less than $d (before or after an
iteration). Setting this param does not guarantee a result of that length, for example son(9000,3)
== 9.
This part might tickle mathematicians:
Note that $d param makes sense when set to 1 or 2, because the chance for a given number to be
longer than 2 digits after an iteration are 0% (at least for base10 numbers). I tested that for all
3 to 6 figure base10 numbers. A 2 digit result was 81.66%, 94.5%, 98.57, 99.666333% likely,
respectively.
You can see, the chances of having a 2 digit number approach 100% as you go higher.
Sum of binary would be interesting...
The $d param also makes sense if you want to limit the length of accepted numbers, in which case it
will just return the same number. Ex: son(9000,4) == 9000.
<?php
test(4);
function test($len) {
$result = array();
$min = pow(10, $len-1);
$max = pow(10, $len);
for($j = 1; $j < 3; $j++) {
for($i = $min; $i < $max; $i++) {
$r = son($i, $j);
$result[$j][0] ++;
$result[$j][1] += (strlen($r) == $j ? 1 : 0);
//echo $j . ', ' . $i . ' = ' . $r . "\r\n";
}
}
foreach($result as $k => $v) {
echo $k . ': %' . (($v[1] / $v[0]) * 100) . "\r\n";
}
}
?>