Inverse factorial loop with PHP - php

I got bored and created this script for the sole purpose of just practicing looping. I'm trying to use a factorial number for example 479001600 which is the factorial of 12! and I'm feeding it to the loop to find what number is 479001600 a factorial of. Using the technique 479001600/2 -> 239500800/3 -> 79833600/4 ...-> previous_int/n+1 I've come up with the following code which works only till 12! but fails on 13! onwards:
<?php
function inv($int){
$j=2;
for($i=0;$i<$j;$i++){
$prod = $int/$j;
if($prod !== 1){
$int = $prod;
echo $prod. "<br>";
$j++;
} elseif($prod == 1) {
return $j;
}
}
}
echo inv(6227020800); // 13!
?>
When I try to compute the 6227020800 to 13! I get the following output:
3113510400
1037836800
259459200
51891840
8648640
1235520
154440
17160
1716
156
13
1
0.071428571428571
0.0047619047619048
0.00029761904761905
1.750700280112E-5
9.7261126672891E-7
5.1190066669943E-8
2.5595033334971E-9
1.2188111111891E-10
...etc
Even though it gets to the integer 1 through the loop division, it carries on ignoring the if statement. Is there something I'm doing wrong? Any help will be appreciated, also, I want to avoid using the gmp_ functions.

This is because 1 and 0.071428571428571 are not the same type.
Your comparison operator, !==, checks that the values are identical and since they are of different types, the check fails. To see for yourself try this:
echo gettype(1);
echo gettype(0.12);

Related

I need a program in PHP, where I search a number in a series mentioned and then give output as the index on which it is present?

I need a program in PHP, when I search a number in a given series like 1,3,7,15,31... and if it is present in the series then give output as the index on which it is present in series?
LIKE I HAVE DONE SOMETHING TO DO THIS BUT FAILED.
<?php
function test1($n) {
for($i=1;$i<=$n;$i=$c) {
$c =1 + (2 * $i);
}
}
function test2($p) {
global $c,$n;
$input=array(1);
$in=array_push($input,$c);
$k=array_search($p,$input);
$flipped = array_flip($k);
var_dump($flipped);
}
test1(1000000);
test2(45);
Like in this program I had made two functions and in FUNCTION test1 I made a formula to make the series 1,3,7,15,31,63,127.... and in FUNCTION test2 I insert a number in form of parameter and want to SEARCH that number in the series that I form above and the I want OUTPUT as the index of that number searched.
Also if the number is not present in the series then I want the output as the nearest number of the number I search.
HELP.!!!
Thank You
You've got a few problems with this code.
function test1($n) {
for($i=1;$i<=$n;$i=$c) {
$c =1 + (2 * $i);
}
}
The first problem here is that you don't do anything with $c each time you increment it. You should probably be pushing it into an array of series integers.
Secondly you don't return a result, so you can't actually use the series you would've created.
You could use something like this instead:
function test1($limit) {
$series = [];
for ($i = 1; $i <= $limit; $i = $i * 2 + 1) {
$series[] = $i;
}
return $series;
}
Next, your test2 function:
function test2($p) {
global $c,$n;
$input=array(1);
$in=array_push($input,$c);
$k=array_search($p,$input);
$flipped = array_flip($k);
var_dump($flipped);
}
Ok, first don't use global variables. Pass the ones you need in as arguments and again, return the result. To be perfectly honest, I'm not entirely sure what this function is supposed to do. All you need is the array_search call which "searches the array for a given value and returns the first corresponding key if successful".
For example:
function test2($series, $number) {
return array_search($number, $series);
}
Using these, you can do something like this:
$series = test1(1000000);
var_dump(test2($series, 45)); // bool(false)
var_dump(test2($series, 31)); // int(4)
Also if the number is not present in the series then I want the output as the nearest number of the number I search.
Ok, you'll need to write some custom logic for this. I suggest you run your array_search check, then if it returns false you loop through your series and check the following criteria:
The previous series entry is lower than your number
The next series entry is higher than your number
Then return whichever of those two has a smaller absolute difference when you subtract the series entry from your number.
I'm not going to write an example for this because it smells a bit like a school assignment, which I'm sure you're capable of doing =) good luck.

Printing Output before getting recursion value

The output of the following is 1102555. How is it possible? Does recursion takes place first or echo?
abc(11);
function abc($a){
if(intval($a/2) != 0){
echo abc(intval($a/2)) + 10 * ($a/2);
}else{
echo 1;
}
}
In your case , recursion will take place first, because everytime you call the function abc with $a/2 greater than 0, the abc() in the echo gets called again and again till the value of $a/2 is less than 0.
Recursion is first in this case. Expression is evaluated from inner most to outer. So in this case it's something like this:
$a/2
intval(RESULT_OF_PREVIOUS_HERE)
abc(RESULT_OF_PREVIOUS_HERE
$a/2
10 * (RESULT_OF_PREVIOUS_HERE)
echo RESULT_OF_PREVIOUS_HERE

php count returns 1 for empty array solution on server

I need to php count returns 0 for empty using server or mysql. Actually, in my case lot of places i have used count function, when i am upload my code to client server php count returns 1 for empty.So that it is create many issue. If any solution then please reply me. I am not want to change all the places where count used.
If i am not getting you wrong, you are passing a non-array element to count.
Look at following example code..
Code 1:
$var = false;
echo count($var); // print 1
Code 2:
$var = array();
echo count($var); // print 0
Code 3:
$var = array('');
echo count($var); // print 1
So better you should check whether the element is an array or not.
if(is_array($var))
{
$var = array_filter($var);
echo count($var);
}
else
{
echo 0;
}
See Codepad.

lost var in php

I am fairly new to PHP and Yii, and the problem that I am not nor as the question in google, so the only thing I can think of is to ask the question to this list that I have solved many problems.
The issue is as follows: in the code that I attached, I read several records that I keep in array and after the process.
Well, if you look at the debug entries in foreach in he first, all goes well and the variable $items is loaded, but when I get to the second debug $items variable has the correct number of elements, but the elements are empty : count ($items) = 2 but $items[0] and $items[1] are null
$idiomas=CListaMidiomas::model()->findAll();
$items=array();
$nombre=array();
$a=0;
foreach ($idiomas as $idioma){
$nombre[$a]=$idioma->sIdioma;
$items[$a]=TblCategoriastexto::model()->findAll(
array('condition'=>'id='.$data->id.' AND idIdioma='.$idioma->id_idioma));
echo "<br>---AAAAAAAAAAA--".$a."-----------<br>";
CVarDumper::dump($items); //in this moment is correct
if (empty($items[$a]) ||$items[$a]==null ){ // not enter because $items have content
$items[$a]=new TblCategoriastexto();
$items[$a]->idIdioma=$idioma->id_idioma;
}
$a++;
}
echo ">>>>>>>>>>>>>>>".count($items) ; //<<<<<<<<<<present 2
CVarDumper::dump($items); // but in this moment t0 2 are null
for ($a=0;$a<count($items) ;$a++){
echo "<b>".CHtml::encode($nombre[$a]).":</b>";
$out="";
$item=$items[$a];
echo "<br>-----".$a."-----------<br>";
CVarDumper::dump($items[$a]);<<<<<<<<<<<<<<<<<<<<<<<<null
for ($b=1;$b<=20;$b++){
$campo="tc".$b;
$out.=$items[$a]->$campo . ",";<<<<<<<<<<<<<<<<error
}
echo CHtml::encode($out);
echo"<br>";
}
This line: if (empty($items[$a]) ||$items[$a]=null ){ will always assign $items[$a] to null.
To compare values, use the comparison (for equality) operator, == instead of the assignment operator =.
Try changing this line:
if(isset($items[$a]->$campo)) {
$out.=$items[$a]->$campo . ",";
}

if no row return then it's false when using php with mysql

I noticed that a lot of tutorial instructions often have this code:
$sql="SELECT * from table";
$num=mysql_num_rows();
if ($num > 0)
{
do something
}
Why do they have to use that condition "if ($num > 0)" when I write this code that I think is compact and readable:
$sql="SELECT * from table";
$itExists=mysql_num_rows();
if ($itExists)
{
do something
}
does mysql_num_rows ever return a negative integer? Doesn't PHP always equate 0 to false? I've used this approach and noticed nothing different or unusual.
Tutorials probably try to make the code as clear, intuitive and explicit as possible. Using mysql_num_rows, whose name clearly implies an integer, as a boolean, is somewhat counter-intuitive. The comparison with zero is implicit. By contrast, if it is perceived as a number, then checking that it’s greater than zero is intuitive and obvious and therefore less confusing.
Why would you assign the number of rows returned to a variable with a bool name like itExists? By doing this you are making information that could be used later less useful. It's better to assign the number of rows (mysql_num_rows()) to a variable that says it holds a number of rows (numRows or in this case num).
Having something like itExists assigned to 4, 5 or 6 isn't good practice. It's in this way that the first method is better.
$pages = $numRows / $itemsPerPage;
//works better than...
$pages = $itExists / $itemsPerPage;
Both ways work just fine. I don't know why you wouldn't choose the second method.
According to http://php.net/manual/en/function.mysql-num-rows.php, it returns FALSE on an error. I'm pretty sure FALSE > 0 is FALSE, so the two are equivalent.
OTOH, it's traditional in other languages (and possibly in older versions of PHP) to return negative numbers on an error. Some OpenSSL signature-verification functions return 1 for "valid", 0 for "invalid", and -1 for "error". It's a coding style thing.
PD. If you only need to check if there are rows, using mysql_num_rows is not very efficient, it is better to count within the SQL statement:
SELECT COUNT(*) FROM table
See:
- MySQL PHP count(*) returning something weird
- https://stackoverflow.com/search?q=php+mysql+count+rows
Doesn't PHP always equate 0 to false?
Not always:
$a = 0;
if (!$a) echo 'pass <br />'; else echo 'fails <br />';
if ($a == false) echo 'pass <br />'; else echo 'fails <br />';
if ($a === false) echo 'pass <br />'; else echo 'fails <br />';
See: http://php.net/manual/en/language.operators.comparison.php

Categories