note 71782 deleted from language.operators.arithmetic by hholzgra
| From: | hholzgra@php.net | Date: | Thu, 02 Aug 2012 15:06:12 +0000 |
| Subject: | note 71782 deleted from language.operators.arithmetic by hholzgra | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-189811@lists.php.net to get a copy of this message | ||
Note Submitter: gilthansREMOVEME at gmail dot com
----
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.