note 72265 added to function.is-numeric

From: Date: Wed, 10 Jan 2007 03:22:19 +0000
Subject: note 72265 added to function.is-numeric
Groups: php.notes 
Request: Send a blank email to php-notes+get-121518@lists.php.net to get a copy of this message
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"; } } ?> ---- Server IP: 66.163.161.117 Probable Submitter: 74.118.123.241 ---- Manual Page -- http://www.php.net/manual/en/function.is-numeric.php Edit -- https://master.php.net/note/edit/72265 Del: integrated -- https://master.php.net/note/delete/72265/integrated Del: useless -- https://master.php.net/note/delete/72265/useless Del: bad code -- https://master.php.net/note/delete/72265/bad+code Del: spam -- https://master.php.net/note/delete/72265/spam Del: non-english -- https://master.php.net/note/delete/72265/non-english Del: in docs -- https://master.php.net/note/delete/72265/in+docs Del: other reasons-- https://master.php.net/note/delete/72265 Reject -- https://master.php.net/note/reject/72265 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#121518) next »