I'm working on some PHP code but I'm stuck with a logic.
I need to find out the number of squares from a rectangle.
I'm unable to implement this in PHP.
Please help.
I tried this:
function getcount($length,$breadth,$count=0){
$min=min($length,$breadth);
if($length>$breadth){
$length=$length-$min;
$count++;
return getcount($length,$breadth,$count);
}
else if($breadth>$length){
$breadth=$breadth-$min;
$count++;
return getcount($length,$breadth,$count);
}
else{
$count+=($length/$min);
}
return $count;
}
But some how it doesn't pass all the use cases.
And i do not know on which use cases, it fails?
I think the easiest way to calculate the number of squares in a rectangle is to substract the found squares from it while it disappears completely.
It works fine for me:
function getcount($width,$height) {
$total=0;
while($width && $height)
{
if($width>$height)
{
$width-=$height;
}
else if($height>$width)
{
$height-=$width;
}
else
{
$width=0;
$height=0;
}
$total+=1;
}
return $total;
}
echo getcount(5,3)."<br/>";
echo getcount(5,5)."<br/>";
echo getcount(11,5)."<br/>";
Output:
4
1
7
In my opinion there is nothing wrong in your code. The output from the code in OP is exactly the same as the output of the code in the accepted answer. You can run this (where getcount() is the function from OP and getcount2() is the function from the Balázs Varga's answer):
for ($i=0; $i<10000; $i++)
{
$a=mt_rand(1,50);
$b=mt_rand(1,50);
$r1 = getcount($a, $b);
$r2 = getcount2($b, $b);
if ($r1 != $r2)
{
echo "D'oh!";
}
}
and it will not return anything at all.
The only flaw is your code will throw a warning message when you run getcount(0, 0).
Also, the second line in your code ($min=min($length,$breadth);) is a bit redundant. You can write the same this way:
function getcount($length,$breadth,$count=0){
if($length>$breadth){
$length=$length-$breadth;
$count++;
return getcount($length,$breadth,$count);
}
else if($breadth>$length){
$breadth=$breadth-$length;
$count++;
return getcount($length,$breadth,$count);
}
else if ($breadth!=0){
$count++; // there is no need to divide two same numbers, right?
}
return $count;
}
Related
The function for the primes is clear, so I omitted it.
$a=10;
$z=30;
for($prime = $a; $prime<$z; $prime++)
{ if
(Prim($prime) == TRUE)
{ echo $prime."<br/>";}}
Now I want to select the next term of the sequence as well, in order to perform an operation between the variable $prime and $next_prime, as long as the loop goes on - like for example:
$prime_gap=bcsub($next_prime, $prime);
Whatever solutions I find and I try, it's never the proper one. It's surely very simple but I am already desperate.
I would suggest you start by creating a next_prime() function. Like this, for example:
function next_prime($n) {
do {
$n++;
} while (!Prim($n));
return $n;
}
Then you can refactor your code quite easily:
$a=10;
$z=30;
for ($p1=next_prime($a),$p2=next_prime($p1); $p2<$z; $p1=$p2,$p2=next_prime($p2)) {
if (some_function($p1, $p2)) {
echo "I like $p1 and $p2\n";
}
}
The if I add in the for loop is not so nice, but if you want something simple and easy to understand, you can still use it (I switch the name from $prime & $next_prime to $prime & $previous_prime, I think it makes more sense)
$a=10;
$z=30;
$previous_prime = 0;
for($prime = $a; $prime<$z; $prime++)
{
if (Prim($prime) == TRUE)
{
echo $prime."<br/>";
if ($previous_prime == 0) {
$previous_prime = $prime
} else
{
$prime_gap = $prime - $previous_prime;
$previous_prime = $prime;
}
}
}
I was trying to make a program to do synthetic division which requires factoring so I wrote this function to factor an integer which works, but it never changes the values of the php array $factors. Any help will be greatly appreciated.
$factors=array();
$i;
function factor($x){
if($x==0){
echo "(0,0)";
} else {
$n=false;
if($x<0) {
$x=abs($x);
$n=true;
}
for($i=2; $i<=$x; $i++) {
if($x%$i==0){
if($n){
$factors[(count($factors))]=(-1*($x/$i));
$factors[(count($factors))]=($i);
$factors[(count($factors))]=($x/$i);
$factors[(count($factors))]=(-1*$i);
} else {
$factors[(count($factors))]=($x/$i);
$factors[(count($factors))]=($i);
}
}
}
}
}
factor(-4);
Try this
function factor($x){
$factors=array();
if($x==0){
echo "(0,0)";
} else {
$n=false;
if($x<0) {
$x=abs($x);
$n=true;
}
for($i=2; $i<=$x; $i++) {
if($x%$i==0){
if($n){
$factors[(count($factors))]=(-1*($x/$i));
$factors[(count($factors))]=($i);
$factors[(count($factors))]=($x/$i);
$factors[(count($factors))]=(-1*$i);
} else {
$factors[(count($factors))]=($x/$i);
$factors[(count($factors))]=($i);
}
}
} //end for
echo '(' . implode(',', $factors). ')';
} //end if $x == 0
}
factor(-4);
$factors is outside the scope of the function, besides that you were not returning or outputting anything. Seeing as you echo (0,0) I assumed you wanted it echoed such as (2,4,8) etc. Which you can do with implode..
my problem is, i have a form which i fill blabla and after i submit i need to check if the var '$number' contains only 9 numbers. which means that if it contains at least 1 letter or has less or more than 9 length it should return false, else it should return true;
this is what i got so far:
if (!is_numeric ($number) {
//do
} else {
}
1st problem: This code should take care of the only numbers part but it doesnt, it always returns false.
2nd: do you guys know of any way to take care of the 9 digits only verification?
thanks and sorry for my bad english, not my native language :P
Your number may contain unwanted whitespaces which cause the is_numeric() test not to work properly
So do the following: $number = trim($number); to remove them.
Then indeed this snippet is good to check if your variable is a number:
if (!is_numeric ($number)) {
//do
} else {
}
And for the number digits do a if statement to see if your number is between 100000000 and 999999999
So the full code will be:
$number = trim($number);
if (!is_numeric ($number)) {
//do
} else {
if ($number >= 100000000 && $number <= 999999999) {
// Everything is ok
} else {
}
}
Didn't understood your complete question coz of you native language :p, but i think you want this:
if (is_numeric($number) {
if(strlen($number) == 9){
return true;
} else {
return false;
}
} else {
echo 'Not a number';
}
Check if it contains digits and check whether its exactly contains 9.
$number = '123456789';
if(!preg_match('/^\d{9}$/', $number)) {
echo 'not ok';
} else {
echo 'ok';
}
I was wondering if there is any way to detect if a number is negative in PHP?
I have the following code:
$profitloss = $result->date_sold_price - $result->date_bought_price;
I need to find out if $profitloss is negative and if it is, I need to echo out that it is.
if ($profitloss < 0)
{
echo "The profitloss is negative";
}
Edit: I feel like this was too simple an answer for the rep so here's something that you may also find helpful.
In PHP we can find the absolute value of an integer by using the abs() function. For example if I were trying to work out the difference between two figures I could do this:
$turnover = 10000;
$overheads = 12500;
$difference = abs($turnover-$overheads);
echo "The Difference is ".$difference;
This would produce The Difference is 2500.
I believe this is what you were looking for:
class Expression {
protected $expression;
protected $result;
public function __construct($expression) {
$this->expression = $expression;
}
public function evaluate() {
$this->result = eval("return ".$this->expression.";");
return $this;
}
public function getResult() {
return $this->result;
}
}
class NegativeFinder {
protected $expressionObj;
public function __construct(Expression $expressionObj) {
$this->expressionObj = $expressionObj;
}
public function isItNegative() {
$result = $this->expressionObj->evaluate()->getResult();
if($this->hasMinusSign($result)) {
return true;
} else {
return false;
}
}
protected function hasMinusSign($value) {
return (substr(strval($value), 0, 1) == "-");
}
}
Usage:
$soldPrice = 1;
$boughtPrice = 2;
$negativeFinderObj = new NegativeFinder(new Expression("$soldPrice - $boughtPrice"));
echo ($negativeFinderObj->isItNegative()) ? "It is negative!" : "It is not negative :(";
Do however note that eval is a dangerous function, therefore use it only if you really, really need to find out if a number is negative.
:-)
if(x < 0)
if(abs(x) != x)
if(substr(strval(x), 0, 1) == "-")
You could check if $profitloss < 0
if ($profitloss < 0):
echo "Less than 0\n";
endif;
if ( $profitloss < 0 ) {
echo "negative";
};
Don't get me wrong, but you can do this way ;)
function nagitive_check($value){
if (isset($value)){
if (substr(strval($value), 0, 1) == "-"){
return 'It is negative<br>';
} else {
return 'It is not negative!<br>';
}
}
}
Output:
echo nagitive_check(-100); // It is negative
echo nagitive_check(200); // It is not negative!
echo nagitive_check(200-300); // It is negative
echo nagitive_check(200-300+1000); // It is not negative!
Just multiply the number by -1 and check if the result is positive.
You could use a ternary operator like this one, to make it a one liner.
echo ($profitloss < 0) ? 'false' : 'true';
I assume that the main idea is to find if number is negative and display it in correct format.
For those who use PHP5.3 might be interested in using Number Formatter Class - http://php.net/manual/en/class.numberformatter.php. This function, as well as range of other useful things, can format your number.
$profitLoss = 25000 - 55000;
$a= new \NumberFormatter("en-UK", \NumberFormatter::CURRENCY);
$a->formatCurrency($profitLoss, 'EUR');
// would display (€30,000.00)
Here also a reference to why brackets are used for negative numbers:
http://www.open.edu/openlearn/money-management/introduction-bookkeeping-and-accounting/content-section-1.7
Can be easily achieved with a ternary operator.
$is_negative = $profitloss < 0 ? true : false;
I wrote a Helper function for my Laravel project but can be used anywhere.
function isNegative($value){
if(isset($value)) {
if ((int)$value > 0) {
return false;
}
return (int)$value < 0 && substr(strval($value), 0, 1) === "-";
}
}
I'm in PHP working on an Euler problem. I have this function so far:
<?php
$biggest = 0;
$counter = 1;
function test($i){
global $biggest;
global $counter;
if ($i == 1) {
echo "I'm done! Took me $biggest steps";
}
else {
if ($i%2 == 0) {
$counter = $counter + 1;
if ($counter>$biggest) {
$biggest = $counter;
}
test($i/2);
}
else {
$counter = $counter + 1;
if ($counter>$biggest) {
$biggest = $counter;
}
test(3*$i+1);
}
}
}
test(13);
?>
I have the problem mostly licked, but I can't seem to get back at the original input. The question is "When you have a number, if odd get 3n+1, when even, get n/2, do until returns 1. What starting value yields the most "steps" before you get to one?" I currently am returning the number of steps, but I keep resetting $i as I recurse, so I can't record what starting # yielded my $biggest number of steps.
How can I keep track of that number, but also not have it destroyed at the next instance of the loop? (I'll eventually wrap this in a for ($i=1, $i<1000000, $i++) loop)
Thanks!
A common approach is to pass the original argument through each time, so that when eventually you get to your base case, you still have it available. A primitive (and almost entirely unrelated example):
<?php
function fact($n) {
if($n == 1) return 1;
else return $n * fact($n - 1);
}
?>
This is an extremely basic implementation of the factorial function in PHP. Now say you wanted for whatever reason to have the initial value available in the final step: you'd build a wrapper function fact($n) that would call something like memory_fact($n, $initial):
<?php
function fact($n) {
return memory_fact($n, $n);
}
function memory_fact($n, $initial) {
if($n == 1) return 1;
else return $n * memory_fact($n - 1, $initial);
}
?>
This way, memory_fact always knows where it started.
It's easy, just pass it around as a parameter! Here's some python-ish pseudocode:
def func(start, arg):
if foo(arg):
return func(start, arg+1)
else:
return [start, arg]
You don't need the globals; globals are evil. Try returning something useful from test(). Also, you'll find the test() above wastes many cycles. Try using memoization.
Here's a memoization example for calculating Fibonacci numbers:
function fib($n) {
static $data = array(1, 1);
if (!isset($data[$n])) {
$data[$n] = fib($n-1) + fib($n-2);
}
return $data[$n];
}
Note that there are other time-efficent constant-space approaches to handle Fibonacci numbers (including one in O(log n) time), but the Collatz conjecture is a little trickier.