note 71782 added to language.operators.arithmetic
| From: | gilthansREMOVEME at gmail dot com | Date: | Fri, 15 Dec 2006 15:43:53 +0000 |
| Subject: | note 71782 added to language.operators.arithmetic | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-120637@lists.php.net to get a copy of this message | ||
1) About integer division: here's a function that neatly solves this. It is somewhat slower
than normal division, but is failsafe.
<?php
function integer_divide($x, $y){
//Returns the integer division of $x/$y.
$t = 1;
if($y == 0 || $x == 0)
return 0;
if($x < 0 XOR $y < 0) //Mistaken the XOR in the last instance...
$t = -1;
$x = abs($x);
$y = abs($y);
$ret = 0;
while(($ret+1)*$y <= $x)
$ret++;
return $t*$ret;
}
?>
2) adam.pippin noted about number factoration, however the function returns alot of sequences in
text form. This one returns an Array with all the factored numbers of a number. For example,
factor(50) would return Array(2, 5, 5).
<?php
function factor($n){
$ret = Array();
$i = 2;
$m = $n/2;
while($i <= $m){
if(!($n%$i))
$ret = array_merge($ret, factor($i), factor($n/$i));
if($i%2)
$i+=2; //$i is impair
else
$i++;
//Ideally, you'd only run through prime numbers, but there is no way to tell what is
the next prime number; we can be sure, however, that the pair ones aren't prime.
$m = $n/$i; //If $n isn't divisible by $i, it be assumed it isn't divisible by any
number bigger than $n/$i, and if it is divisible by $i, $n/$i is already put in. The derivation for
this isn't too complex. This drastically reduces the number of numbers we have to go through
during the factoration.
}
if(empty($ret))
return Array($n);
return $ret;
}
?>
This has only been tested for integers, factoration for floats should include some way to identify
the divisor.
Hope this saves someone some headaches.
----
Server IP: 192.117.122.43
Probable Submitter: 87.69.10.151
----
Manual Page -- http://www.php.net/manual/en/language.operators.arithmetic.php
Edit -- https://master.php.net/note/edit/71782
Del: integrated -- https://master.php.net/note/delete/71782/integrated
Del: useless -- https://master.php.net/note/delete/71782/useless
Del: bad code -- https://master.php.net/note/delete/71782/bad+code
Del: spam -- https://master.php.net/note/delete/71782/spam
Del: non-english -- https://master.php.net/note/delete/71782/non-english
Del: in docs -- https://master.php.net/note/delete/71782/in+docs
Del: other reasons-- https://master.php.net/note/delete/71782
Reject -- https://master.php.net/note/reject/71782
Search -- https://master.php.net/manage/user-notes.php