PHP: Simple recursive function into iterative function - php

I was going to do it in C but was confused, so I turned to PHP and was able to copy a recursive function to do this. I am converting an integer into a string with math. Here it is:
function intToString($myDecimal){
if($myDecimal < 10) {
return $myDecimal;
}
return intToString(($myDecimal / 10)) . ($myDecimal % 10);
}
I was able to convert a recursive factorial function before.. but with this I just have no clue.. My attempt is as follows:
function intToStringIter($myDecimal){
$out = "";
while($myDecimal > 10) {
$myDecimal /= 10;
$out .= $myDecimal;
}
$out .= $myDecimal % 10;
return $out;
}
I think I am too tired to see the proper logic at the moment.. It returns 22 instead of 20, I cannot wrap my head around what is correct. Do you see what I am doing wrong?

If you're looking for a conversion to string for big unsigned integers, the code is actually:
function intToString($myDecimal)
{
return sprintf('%u', $myDecimal);
}
If you need to do it with iteration:
function intToString($myDecimal)
{
$result = '';
while ($myDecimal > 9) {
$result = ($myDecimal % 10) . $result;
$myDecimal /= 10;
}
return $myDecimal . $result;
}
UPDATE: My bad, digits were inserted in reversed order. Now it should work. Sorry, untested too.

PHP is not very strict with variables. An integer will become an float if the situation likes it. In your code, $myDecimal /= 10 could make a float of $myDecimal. The following forces $myDecimal to stay an integer. Note: you should pass only integers, if you're passing 9.99, the output would still be 9.99 because 9.99 < 10.
function intToStringIter($myDecimal){
$out = "";
while($myDecimal >= 10) {
$myDecimal = (int) ($myDecimal / 10);
$out .= $myDecimal;
}
$out .= $myDecimal % 10;
return $out;
}

Related

PHP loop isn't working, what am I doing wrong?

I am building a function that would receive 2 params, a string and a number.
it would basically print the first letters $n of $s.
I need to run a loop, please don't advise other non looping methods.
And yes, I need to keep the loop true throughout the function, it's suppose to close when the if is met.
For some reason the loop isn't closing, even though there's a return in the if condition that is being met when $stringCounter equals $n (=10 in this example.)
function printCounter($s, $n)
{
$stringCaller = '';
$stringCounter = strlen($stringCaller);
while (1) {
$stringCaller .= $s;
if ($stringCounter == $n) {
return $stringCaller;
}
}
}
printCounter('aba', '10');
You should imove the calc of $stringCounter inside the loop otherwise this never change
$stringCaller = '';
while (1) {
$stringCounter = strlen($stringCaller);
$stringCaller .= $s;
if ($stringCounter >= $n) {
return $stringCaller;
}
}
On my oppinion, TS is searching next approach:
function printCounter($s, $n)
{
$result = '';
$str_lenght = strlen($s);
if(!$str_lenght) {
return $result;
}
while (true) {
$result .= $s;
$result_lenght = strlen($result);
if($result_lenght/$str_lenght >= $n) {
return $result_lenght;
}
}
}
echo printCounter('aba', '10');
exit;
You can fix part of the issue by updating $stringCounter inside the loop.
function printCounter($s, $n)
{
$stringCaller = '';
while (1) {
$stringCaller .= $s;
$stringCounter = strlen($stringCaller); // check strlen after each addition of $s
if ($stringCounter == $n) {
return $stringCaller;
}
}
}
However, even after you fix that issue, there will still be cases where your loop will never exit (such as the example in your question) because $stringCounter can only equal $n if $n is a multiple of strlen($s).
For the example printCounter('aba', '10');
Iteration $stringCounter ($stringCounter == $n)
1 3 false
2 6 false
3 9 false
4 12 false
Obviously $stringCounter will only get farther away from $n from that point.
So to ensure that the function will exit, check for inequality instead with:
if ($stringCounter >= $n) {
If you need the function to return exactly $n characters, the function will need to be a little more complex and take a substring of $s to make up the remaining characters when $stringCounter + strlen($s) will be greater than $n, or return an $n character substring of your result like this:
function printCounter($s, $n)
{
$result = '';
while (1) {
$result .= $s;
if (strlen($result) >= $n) {
return substr($result, 0, $n);
}
}
}

How I can create my own pow function using PHP?

I want to create a function in which I put two values (value and its power - Example function: multiply(3, 3) result 27). I have tried so far but failed, I have searched using Google but I have been unable to find any result because I don't know the name of this function.
What I want exactly:
3,3 => 3 x 3 x 3 = 27
4,4 => 4 x 4 x 4 x 4 = 256
What I tried:
function multiply($value,$power){
for($x = 1; $x <= $value; $x++ ){
return $c = $value * $power;
}
}
echo multiply(3,3);
The answer has already been accepted, but I had to come here and say that all answers here use a bad algorithm. There are better ones. Including very simple ones, like exponentiation by squaring that reduces the complexity from O(power) to O(log(power)).
The idea is to square the base while dividing the exponent by 2. For example
3^8 = 9^4 = 81^2 = 6561
There is a special case when the exponent is odd. In this case, you must store a separate variable to represent this factor:
2^10 = 4^5 = 16^2 * 4 = 256 * 4 = 1024
PHP isn't one of my strong skills, but the final algorithm is as simple as:
function multiply($value, $power){
$free = 1;
while ($power > 1) {
if ($power % 2 == 1)
$free *= $value;
$value *= $value;
$power >>= 1; //integer divison by 2
}
return $value*$free;
}
echo multiply(3, 3) . "\n";
echo multiply(2, 10) . "\n";
echo multiply(3, 8) . "\n";
Oopsika, couldn't have asked a more obvious question. Use the built-in function named pow (as in a lot of languages)
echo pow(3, 3);
Edit
Let's create our own function.
function raiseToPower($base,$exponent)
{
// multiply the base to itself exponent number of times
$result=1;
for($i=1;$i<=$exponent;$i++)
{
$result = $result * $base;
}
return $result;
}
function exponent($value,$power)
{
$c=1;
for($x = 1; $x <= $power; $x++ )
{
$c = $value * $c;
}
return $c;
}
If you have PHP >= 5.6 you can use the ** operator
$a ** $b Exponentiation Result of raising $a to the $b'th power.
echo 2 ** 3;
If you have PHP < 5.6 you can use pow:
number pow ( number $base , number $exp )
echo pow(2, 3);
Your own function is:
function multiply($value, $power) {
$result = 1;
for($x = 1; $x <= $power; $x++){
$result *= $value;
}
return $result;
}
echo multiply(3,3);
Read more at:
http://php.net/manual/en/language.operators.arithmetic.php
http://php.net/manual/en/function.pow.php
Just try to run this code I hope your problem will be solved.
If you defining any function then you have to call it return value.
<?php
function multiply($value,$exp)
{ $temp=1;
if($exp==0)
return $temp;
else
{
for($i=1;$i<=$exp;$i++)
$temp=$temp*$value;
return $temp;
}
}
echo multiply(5,6);
?>
echo "Enter number (will be mutiplied):".PHP_EOL;
$value = (int) readline("> ");
echo "Enter number for multiplier:".PHP_EOL;
$multiplier = (int) readline("> ");
function power(int $i, int $n):int {
$result =1;
for ($int = 1; $int < $n; $int++){
$result *= $i;
}
return $result;
}
echo power($value,$multiplier);

PHP check if is integer

I have the following calculation:
$this->count = float(44.28)
$multiple = float(0.36)
$calc = $this->count / $multiple;
$calc = 44.28 / 0.36 = 123
Now I want to check if my variable $calc is integer (has decimals) or not.
I tried doing if(is_int()) {} but that doesn't work because $calc = (float)123.
Also tried this-
if($calc == round($calc))
{
die('is integer');
}
else
{
die('is float);
}
but that also doesn't work because it returns in every case 'is float'. In the case above that should'n be true because 123 is the same as 123 after rounding.
Try-
if ((string)(int) $calc === (string)$calc) {
//it is an integer
}else{
//it is a float
}
Demo
As CodeBird pointed out in a comment to the question, floating points can exhibit unexpected behaviour due to precision "errors".
e.g.
<?php
$x = 1.4-0.5;
$z = 0.9;
echo $x, ' ', $z, ' ', $x==$z ? 'yes':'no';
prints on my machine (win8, x64 but 32bit build of php)
0.9 0.9 no
took a while to find a (hopefully correct) example that is a) relevant to this question and b) obvious (I think x / y * y is obvious enough).
again this was tested on a 32bit build on a 64bit windows 8
<?php
$y = 0.01; // some mambojambo here...
for($i=1; $i<31; $i++) { // ... because ...
$y += 0.01; // ... just writing ...
} // ... $y = 0.31000 didn't work
$x = 5.0 / $y;
$x *= $y;
echo 'x=', $x, "\r\n";
var_dump((int)$x==$x);
and the output is
x=5
bool(false)
Depending on what you're trying to achieve it might be necessary to check if the value is within a certain range of an integer (or it might be just a marginalia on the other side of the spectrum ;-) ), e.g.
function is_intval($x, $epsilon = 0.00001) {
$x = abs($x - round($x));
return $x < $epsilon;
};
and you might also take a look at some arbitrary precision library, e.g. the bcmath extension where you can set "the scale of precision".
You can do it using ((int) $var == $var)
$var = 9;
echo ((int) $var == $var) ? 'true' : 'false';
//Will print true;
$var = 9.6;
echo ((int) $var == $var) ? 'true' : 'false';
//Will print false;
Basically you check if the int value of $var equal to $var
round() will return a float. This is because you can set the number of decimals.
You could use a regex:
if(preg_match('~^[0-9]+$~', $calc))
PHP will convert $calc automatically into a string when passing it to preg_match().
You can use number_format() to convert number into correct format and then work like this
$count = (float)(44.28);
$multiple = (float)(0.36);
$calc = $count / $multiple;
//$calc = 44.28 / 0.36 = 123
$calc = number_format($calc, 2, '.', '');
if(($calc) == round($calc))
die("is integer");
else
die("is not integer");
Demo
Ok I guess I'am pretty late to the party but this is a alternative using fmod() which is a modulo operation. I simply store the fraction after the calculation of 2 variables and check if they are > 0 which would imply it is a float.
<?php
class booHoo{
public function __construct($numberUno, $numberDos) {
$this->numberUno= $numberUno;
$this->numberDos= $numberDos;
}
public function compare() {
$fraction = fmod($this->numberUno, $this->numberDos);
if($fraction > 0) {
echo 'is floating point';
} else {
echo 'is Integer';
}
}
}
$check= new booHoo(5, 0.26);
$check->compare();
Eval here
Edit: Reminder Fmod will use a division to compare numbers the whole documentation can be found here
if (empty($calc - (int)$calc))
{
return true; // is int
}else{
return false; // is no int
}
Try this:
//$calc = 123;
$calc = 123.110;
if(ceil($calc) == $calc)
{
die("is integer");
}
else
{
die("is float");
}
you may use the is_int() function at the place of round() function.
if(is_int($calc)) {
die('is integer');
} else {
die('is float);
}
I think it would help you
A more unorthodox way of checking if a float is also an integer:
// ctype returns bool from a string and that is why use strval
$result = ctype_digit(strval($float));

Convert hexadecimal number to double

The string of the hexadecimal number is like: 0X1.05P+10
The real value of this hexadecimal number is:1044.0
I can convert it using C language with method strtod.
But I can't find the way to convert it in PHP. Can somebody show me how to do it?
value string list:
1. "0X1.FAP+9"
2. "0X1.C4P+9"
3. "0X1.F3P+9"
4. "0X1.05P+10"
I think you'll have to make a custom function for this. So because I'm feeling nice today I custom-made one for you:
function strtod($hex) {
preg_match('#([\da-f]+)\.?([\da-f]*)p#i', $hex, $parts);
$i = 0;
$fractional_part = array_reduce(str_split($parts[2]), function($sum, $part) use (&$i) {
$sum += hexdec($part) * pow(16, --$i);
return $sum;
});
$decimal = (hexdec($parts[1]) + $fractional_part) * pow(2, array_pop(explode('+', $hex)));
return $decimal;
}
foreach(array('0X1.FAP+9', '0X1.C4P+9', '0X1.F3P+9', '0X1.05P+10', '0X1P+0') as $hex) {
var_dump(strtod($hex));
};
For versions below PHP 5.3:
function strtod($hex) {
preg_match('#([\da-f]+)\.?([\da-f]*)p#i', $hex, $parts);
$fractional_part = 0;
foreach(str_split($parts[2]) as $index => $part) {
$fractional_part += hexdec($part) * pow(16, ($index + 1) * -1);
}
$decimal = (hexdec($parts[1]) + $fractional_part) * pow(2, array_pop(explode('+', $hex)));
return $decimal;
}
foreach(array('0X1.FAP+9', '0X1.C4P+9', '0X1.F3P+9', '0X1.05P+10', '0X1P+0') as $hex) {
var_dump(strtod($hex));
};
hexdec(0X1.05P+10)
OK so that looks wrong to me as that doesn't look like a proper hex number but its the hexdec() function you want in php http://php.net/manual/en/function.hexdec.php
echo hexdec("0X1FAP")+9
echo hexdec("0X1C4P")+9
echo hexdec("0X1F3P")+9
echo hexdec("0X105P")+10
decimal = hex
(1044.0)10 = (414)16

Rounding up to next significant figure

I need to round up any integer between 1 and infinity in php to the next significant figure (though in practice I'm unlikely to need to round up infinity, so will be happy to settle on reasonable internal limits) eg:
$x <= 10 ? $x = 10
10 < $x <= 100 ? $x = 100
100 < $x <= 1000 ? $x = 1000
etc.
Round / ceil etc don't seem to do the job quite as planned. A pointer towards the correct algorhythm (or function?) would be much appreciated
i think this method will fix your problem:
function n($nr, $p = 10) {
if($nr <= $p) {
return $p;
}
return n($nr, $p*10);
}
heres the result:
echo n(1);
//output 10
echo n(232);
//output 1000
echo n(89289382);
//output 100000000
$x = pow(10,floor(log10($x)) + (floor(log10($x)) == log10($x) && $x!=1 ? 0:1) );
function my_ceil($in) {
if($in == 1) return $in;
if($in == pow(10, strlen($in)-1)) return $in;
return pow(10, strlen($in));
}
echo my_ceil(11); //100
echo my_ceil(10); //10
I think this is what you're looking for:
echo ceil($x / pow(10, strlen($x))) * pow(10, strlen($x));
Only works when $x is an integer, but you say in your question that that is indeed the case, so there's no issue (unless you try to later use it with numbers containing decimals).
This should do the trick:
<?php
function nextSignificantFeature($number){
$upper = pow(10, strlen($number));
return $number == $upper/10 ? $number : $upper;
}
?>
Actually there is the infinity number in PHP, so the implementation should deal with it as you wrote any number from 1 up to infinity Demo:
<?php
function n($number) {
if ($number < 1) {
throw new InvalidArgumentException('Number must be greater or equal 1.');
}
if ($number === INF) {
return INF;
}
$p = 10;
while($number > ($p*=10));
return $p;
}
echo n(1), "\n";
//output 10
echo n(232), "\n";
//output 1000
echo n(89289382), "\n";
//output 100000000
echo n(INF), "\n";
// output INF
echo n(-INF), "\n";
// throws exception 'InvalidArgumentException' with message 'Number must be greater or equal 1.'
This example does the iterative calculation in PHP userland code. There are some math functions in PHP that can do it inline like pow.

Categories