I want to check if an input variable is in POWER base.
For example :
Input : 25 ;//yes in power pow(5,2)
Input : 26 ;//no not in power
I made a code but its time taking
$var = 25;
$half = round($var / 2);
for($x = 0; $x <= $half; $x++){
for($y = 0; $y <= $half; $y++){
if(pow($x, $y) === $var){
$output = "1";
}
}
}
if(!$output){
echo "0";
}else{
echo "1";
}
You can use sqrt which will return square root of given number, then just check if the returned value is in decimal or not.
$var = 25;
$sqrt = sqrt($var);
if($sqrt !== floor( $sqrt )) {
echo 'no power';
} else {
echo 'power';
}
Related
I get price from database with 9xx items.
I add this on show items page. Using Foreach $rows=$row. vprice is my sellingprice and dprice is my dealerprice
$commisionrate = 30;
$commisionfee = 100;
$fee = $row['dprice'] + $commisionfee;//+100
$x = $row['dprice'];
$y = $x * $commisionrate / 100;
$z = $x + $y;
$rate = $z;//(100*30%)+100
if (($rate > $row['vprice']) && ($fee < $row['vprice'])){
echo $fee;
}elseif (($fee > $row['vprice']) && ($rate < $row['vprice'])){
echo $rate;
}elseif ($row['dprice']=$row['vprice']){
echo $row['dprice'];
}
when I recheck all, I found that few items of $row['dprice'] is not counted and still show by old price. Example that is false: I found vprice is 188 with 80 dprice after calculate should be 104 but not changing with still stay on 80.
$commisionrate = 30;
$commisionfee = 100;
$fee = $row['dprice'] + $commisionfee;//+100
$x = $row['dprice'];
$y = $x * $commisionrate / 100;
$rate = $x + $y;
// You don't need to put nested brackets, it very simple condition
if ($rate > $row['vprice'] && $fee < $row['vprice']){
echo "fee: " . $fee; //add some hint words, so you know which condition fires
// You don't need to put nested brackets, it very simple condition
} elseif ($fee > $row['vprice'] && $rate < $row['vprice']) {
echo "rate: " . echo $rate;
// USE double `==`, because when single `=` used, the condition always returns true and you're confused by your result
} elseif ($row['dprice'] == $row['vprice']) {
echo "row[\'dprice\']: " . $row['dprice'];
// add last else
} else {
// this is helpful for debugging of your possible output, regardless you are awaiting some output here
}
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);
so I am new at the idea of recursion and i wrote this simple code to factor a number ($n) this is the code:
$n = 120;
$y = 1;
function factor($n, $y) {
if($y > $n) {
return 1;
} else {
$x = $n / $y;
list($whole, $dec) = array_pad(explode('.', $x), 2, Null);
if($dec == '') {
echo 'x:' . $x . ' y:' . $y . '</br>';
return factor($n, ($y + 1));
}
}
}
this is what the code outputs:
x:120 y:1
x:60 y:2
x:40 y:3
x:30 y:4
x:24 y:5
x:20 y:6
so my question is why does this stop before it completes?
Your next step would be 120 / 7 which equals 17.142857....
So this check fails and as such the recursion does not happen:
if($dec=='') // $dec would equal to 142857.....
{
echo'x:'.$x.' y:'.$y.'</br>';
return factor($n,($y+1));
}
else
{
$x=$n/$y;
list($whole,$dec)=array_pad(explode('.', number_format($x)), 2, Null);
if($dec=='')
{
echo'x:'.$x.' y:'.$y.'</br>';
return factor($n,($y+1));
}
}
PART OF DECIMAL LIMITATION
There are two things I see wrong with your example:
Your recursion stops the first time it encounters a fractional value. The tail recursion (return factor($n, $y + 1);) only occurs when $dec == ''. Otherwise, the function simply exits. That's why it stops when $y is 7.
Your condition for ending recursion ($y > $n) is incorrect. You want to break the recursion when the divisor is greater than the quotient — i.e., when $y > $x — because that means you've found all the integer factors.
I think this is what you want:
$n = 120;
$y = 1;
function factor($n, $y) {
$x = $n / $y;
if($y > $x) {
return 1;
} else {
list($whole, $dec) = array_pad(explode('.', $x), 2, Null);
if($dec == '') {
echo 'x:' . $x . ' y:' . $y . "</br>\n";
}
return factor($n, ($y + 1));
}
}
echo factor($n, $y);
I got the answer fine, but when I run the following code,
$total = 0;
$x = 0;
for ($i = 1;; $i++)
{
$x = fib($i);
if ($x >= 4000000)
break;
else if ($x % 2 == 0)
$total += $x;
print("fib($i) = ");
print($x);
print(", total = $total");
}
function fib($n)
{
if ($n == 0)
return 0;
else if ($n == 1)
return 1;
else
return fib($n-1) + fib($n-2);
}
I get the warning that I have exceeded the maximum execution time of 30 seconds. Could you give me some pointers on how to improve this algorithm, or pointers on the code itself? The problem is presented here, by the way.
Let's say $i equal to 13. Then $x = fib(13)
Now in the next iteration, $i is equal to 14, and $x = fib(14)
Now, in the next iteration, $i = 15, so we must calculate $x. And $x must be equal to fib(15). Now, wat would be the cheapest way to calculate $x?
(I'm trying not to give the answer away, since that would ruin the puzzle)
Try this, add caching in fib
<?
$total = 0;
$x = 0;
for ($i = 1;; $i++) {
$x = fib($i);
if ($x >= 4000000) break;
else if ($x % 2 == 0) $total += $x;
print("fib($i) = ");
print($x);
print(", total = $total\n");
}
function fib($n) {
static $cache = array();
if (isset($cache[$n])) return $cache[$n];
if ($n == 0) return 0;
else if ($n == 1) return 1;
else {
$ret = fib($n-1) + fib($n-2);
$cache[$n] = $ret;
return $ret;
}
}
Time:
real 0m0.049s
user 0m0.027s
sys 0m0.013s
You'd be better served storing the running total and printing it at the end of your algorithm.
You could also streamline your fib($n) function like this:
function fib($n)
{
if($n>1)
return fib($n-1) + fib($n-2);
else
return 0;
}
That would reduce the number of conditions you'd need to go through considerably.
** Edited now that I re-read the question **
If you really want to print as you go, use the output buffer. at the start use:
ob_start();
and after all execution, use
ob_flush();
flush();
also you can increase your timeout with
set_time_limit(300); //the value is seconds... so this is 5 minutes.
I know I can do this easily by converting the IP addresses to decimal notation first using PHP built in functions like up2long and long2ip. I just want to be able to do the same using the standard IP address notation as an exercise.
The problem I am thinking goes like this: Given an starting IP address, say 192.168.1.100, and an ending IP address, say 201.130.22.10. Make the program that prints all the address numbers in that range (192.168.1.100, 192.168.1.101, … , 201.130.22.9, 201.130.22.10).
I was thinking that maybe the way to go would be to make a nested for loop inside a while condition until the first octet of the starting address matches the first octet of the ending address. Then execute the same block of code for the second octet and so on until the program reaches the ending address and finished.
I just started learning to program recently so it is quite possible that my of thinking and or writing code is far from elegant. If you were to this, how would you do it?
Something like this:
<?php
// works only for valid range
$start_ip = '10.0.0.1';
$end_ip = '10.0.20.1';
$start_arr = explode('.',$start_ip);
$end_arr = explode('.',$end_ip);
while($start_arr <= $end_arr)
{
echo implode('.',$start_arr) . '<br>';
$start_arr[3]++;
if($start_arr[3] == 256)
{
$start_arr[3] = 0;
$start_arr[2]++;
if($start_arr[2] == 256)
{
$start_arr[2] = 0;
$start_arr[1]++;
if($start_arr[1] == 256)
{
$start_arr[1] = 0;
$start_arr[0]++;
}
}
}
}
?>
This is much less complicated:
<?php
// works only for valid range
$start_ip = ip2long('10.0.0.1');
$end_ip = ip2long('10.0.20.1');
while($start_ip <= $end_ip){
echo long2ip($start_ip).'<br>';
$start_ip++;
}
?>
function getInBetweenIPs($startIP,$endIP){
$subIPS = array();
$start_ip = ip2long($startIP);
$end_ip = ip2long($endIP);
while($start_ip <= $end_ip){
$subIPS[]=long2ip($start_ip);
$start_ip++;
}
return $subIPS;
}
Increment (Add to):
<?php
function ipinc($i): string {
$i = explode(".", $i);
$a = $i[0];
$b = $i[1];
$c = $i[2];
$d = $i[3];
$d++;
if ($d > 255) {
$d = 0;
$c++;
}
if ($c > 255) {
$c = 0;
$b++;
}
if ($b > 255) {
$b = 0;
$a++;
}
if ($a > 255) {
die("IPv4 Range Exceeded");
}
return "$a.$b.$c.$d";
}
?>
Decrement (Take from):
<?php
function ipdec($i) {
$i = explode(".", $i);
$a = $i[0];
$b = $i[1];
$c = $i[2];
$d = $i[3];
$d--;
if ($d < 0) {
$d = 255;
$c--;
}
if ($c < 0) {
$c = 255;
$b--;
}
if ($b < 0) {
$b = 255;
$a--;
}
if ($a < 0) {
die("IPv4 Range Exceeded");
}
return "$a.$b.$c.$d";
}
?>
To test both functions, you can write a for loop to generate approximately 16 million IP addresses back and forth, you can pipe the output to a file and store the results that way.
<?php
require 'function.ipinc.php';
require 'function.ipdec.php';
print("Increment:\n");
for ($i = 0, $ip = "100.0.0.0"; $i <= 16777215; $i++) {
print("$ip\n");
$ip = ipinc($ip);
}
print("----------\n");
print("Decrement:\n");
for ($i = 0, $ip = "100.255.255.255"; $i <= 16777215; $i++) {
print("$ip\n");
$ip = ipdec($ip);
}
print("----------\n");
die("Finished!\n");
?>
If you don't like assigning values through variable declarations, modify the functions so you can use pass by reference instead.