Count from 3 in 3 until I reach 10 with php - php

I am trying a basic program to count from 3 in 3 until I reach 10. I tried:
<?php
$a = 0;
$b = 0;
while ($a < 10) {
$a += $b + 3;
echo "$a\n\r";
}
?>
The output is 3, 6, 9, 12. And the expected output would be 3, 6, 9. because I added < 10. Why is it doing this? Sorry for my noob question, but it's confusing: http://codepad.org/Y8yhd0JP

The value of $a is $a=9 in the 3rd iteration, so the loop will continue to go on to add upto 12.
To obtain the result as 3,6,9 check for while($a < 9){...}
<?php
$a = 0;
$b = 0;
while ($a < 9) {
$a += $b + 3;
echo "$a\n\r";
}
?>

This would be better to do with a do-while cycle, with $a initialised to its starting value before the cycle
<?php
$b = 0;
$a += $b + 3;
do {
echo "$a\n\r";
$a += $b + 3;
} while ($a < 10);
?>

The while will check if the value in $a is more than 10.
After the check you add to the value and print it, then check again, if its over 10, it will not do another loop.
So when it prints 12, it will have checked if $a was over 10, which is was not, cause it was 9. Then do the addition and echo and check again and exit.

To start with, note the $b is always 0, so you can eliminate it like this:
$a = 0;
while ($a < 10) {
$a += 3;
echo "$a\n\r";
}
Note that you change the value of $a between the test and the echo. That is probably the reason for your surprise.
A better way to write it would be
for ($a = 3; $a < 10; $a += 3) {
echo "$a\r\n";
}

An uglier solution:
$a = 0;
$b = 0;
while (($a += $b + 3) < 10)
echo "$a\n\r";
I moved the addition in the while loop. Here you dont't have to put the echo in {} because there's only one statement.

in your code you are printing the element after it is increased, so after it prints 9 , it checks the condition ($a < 10) , the condition is true so it proceeds and print 12 , while the next iteration the condition ($a < 10) fails and it stops. this is the reason , you can avoid it by changing your code as follows,
<?php
$a = 0;
$b = 0;
while ($a < 9) {
$a += $b + 3;
echo "$a\n\r";
}
?>
Hope it helps.

Related

PHP calculating two arrays and then add their sum

I want to calculate an array to another array and then add both like this :
Array1(4,8,7,12);
Array2(3,6);
the result is like this :
3x4+3x8+3x7+3x12+6x4+6x8+6x7+6x12 = 279
I tried with this code and since I'm still new with php I still didn't make any tips I'll be glad thanks in advance
<?php
tab1(4,8,7,12);
tab2(3,6);
$s=0;
for($i=0; $i<$tab1[3]; $i++){
for($j=0; $j<$tab2[1]; $j++){
$s = $s + tab[i] * tab[j];
}
echo "$s";
}
?>
This is actually a piece of cake. I am not sure what tab1 means but I assume you are trying to use this function to get an array of desired(input) numbers.
Using a foreach loop to loop over the two arrays, I came up with the code below:
<?php
$a = [4,8,7,12];
$b = [3,6];
$sum = 0;
foreach ($b as $valueInB) {
foreach ($a as $valueInA) {
$sum += $valueInA * $valueInB;
}
}
echo $sum;
?>
which results in:
279
if you are insisting on using a for loop you can run the code below to get the same result:
<?php
$a = [4,8,7,12];
$b = [3,6];
$sum = 0;
$bLength = count($b);
$aLength = count($a);
for ($i=0; $i < $bLength ; $i++) {
$valueInB = $b[$i];
for ($j=0; $j < $aLength ; $j++) {
$valueInA = $a[$j];
$sum += $valueInA * $valueInB;
}
}
echo $sum;
?>
Please note that you should use the count outside of the loop because looping over the array and calling count each time is not an efficient way. (Thanks to Will B for the comment)
For a more simplistic approach without iteration you can use array_sum on the two arrays.
Example: https://3v4l.org/3gtgE
$a = [4,8,7,12];
$b = [3,6];
$c = array_sum($a) * array_sum($b);
var_dump($c);
Result
int(279)
This works because of the order of operations of:
(3*4) + (3*8) + (3*7) + (3*12) + (6*4) + (6*8) + (6*7) + (6*12) = 279
Equates to the same as the sum of a multiplied by the sum of b:
(4+8+7+12) * (3+6) = 279

List of numbers until n divisible by A or B but not divisible by C

I have three integers: A, B, C
I want to print all integers from 1 to range which are divisible by A or B but not by C.
My code
for($n=0; $n < $range; $n++){
if(($n < $a && $n < $b) || ($n % $c == 0)){
return [];
}
if(($n % $a == 0 || $n % $b == 0) && ($n % $c > 0)){
$outputArr[] = $n;
}
}
Is there any more efficient way to do this?
You can speed this up but it is more complicated, especially if you must print these out in order. Here is a method that doesn't print them out in order.
First write a greatest common divisor (gcd) function in PHP, and then write a least common multiple (lcm) function that uses the gcd function. Compute m = lcm(a, b). Iterate over multiples of a and print them out if they are not divisible by c. Next, iterate over multiples of b and print them out if they are not divisible by m or c.
Other optimizations along these lines are possible. For example, you can precompute the multiples of a or b that are not multiples of m and store them in an array. This works if m is not too large, division is more expensive than array access in PHP, and range is significantly larger than m.
PHP version 7 or higher is so fast when only integer operations are used that micro-optimizations are no longer needed.
$res = [];
$a = 9;
$b = 13;
$c = 26;
$range = 10000;
for($n=$a; $n <= $range; $n += $a){
if($n%$c != 0) $res[] = $n;
}
for($n=$b; $n <= $range; $n += $b){
if($n%$c != 0) $res[] = $n;
}
$res = array_unique($res);
sort($res);
This example takes about 1 millisecond to calculate the 1411 values on my 8-year-old system. This time for the presentation of the result is several times greater.
I would use range() and array_filter().
$range = 20;
$A = 2;
$B = 3;
$C = 9;
$nums = array_filter(range(1, $range), function ($x) use ($A, $B, $C) {
return (!($x % $A) || !($x % $B)) && $x % $C;
});
var_dump($nums);
Here is a more optimized solution, that also works efficient when a and b are large. You can simply run through the multiples of a and b:
for($na=$a, $nb=$b; $na <= $range || $nb <= $range; ){
if ($na <= $nb) {
if ($na % $c != 0)
$outputArr[] = $na;
if ($na == $nb)
$nb += $b;
$na += $a;
} else {
if ($nb % $c != 0)
$outputArr[] = $nb;
$nb += $b;
}
}
Each output number is only generated once, and already in the desired order.
If you are afraid the modulo test is slow, you could also have a next multiple of c running along, but that looks like too much overhead.

Checking repeating combination

So I have a program in PHP, which draws three numbers from array, adds them up and checks if sum = 10. If yes, then it should print those numbers on the display.
What I want to do is to check which combination was drawn. For example:
First draw: 1+7+2
Second draw: 5+4+1
Third draw: 1+2+7
First and third had the same numbers, so third shouldn't be shown. Unfortunately, I have no idea how to do it.
My code:
<?PHP
$numb = array(1,2,3,4,5,6,7,8,9,0);
$hm = count($numb);
for ($a=0; $a<$hm;$a++)
for ($b=0; $b<$hm;$b++)
for ($c=0; $c<$hm;$c++)
{
$cnt = $numb[$a]+$numb[$b]+$numb[$c];
if ($cnt == 10)
{
print_r ($numb[$a]);
echo "+";
print_r ($numb[$b]);
echo "+";
print_r ($numb[$c]);
echo "<br>";
}
}
?>
With the provided code, you can simply draw numbers "in order" to avoid duplicates:
$numb = array(0,1,2,3,4,5,6,7,8,9); // <-- must be sorted from lowest to highest
for ($a = 0; $a < $hm; $a++)
for ($b = $a; $b < $hm; $b++) // <-- start from $a
for ($c = $b; $c < $hm; $c++) // <-- start from $b
Thus, the combination 1+2+7 is possible, but not 1+7+2, and also not 7+1+2 etc.

Adding and subtracting within a range of numbers and looping round

I'm wondering how I would go about the addition and subtraction of numbers in a set range and which would loop back on themselves, example below;
Range: 1 - 10
So if I now had the number 7 and added 5 to it, I would want the number go to 2
8, 9, 10, loop around to 1, 2.
And the same if I subtracted, so I have the number 3 and I subtract 4 so I should be left with 9.
2, 1, loop around to 10, 9
I hope this makes sense.
Thanks.
You can use % operator.
It calculates remainder after division.
For example:
$d = 10;
$x = 7;
$y = 5;
echo ($x + $y) % $d;
gives 2;
With negative values you can just remove MINUS
Use the modulus operator.
result = (a + b) % 10;
You can use modulo function like (7+5)%10 = 2
Try this:
$range = range(1,10);
$min = min($range);
$max = max($range);
function operate( $a, $b, $operation ) {
global $max, $min;
switch( $operation ) {
case '+':
$a += $b;
break;
case '-':
$a -= $b;
break;
}
if( $a < $min ) {
return $max + $a;
} else if( $a > $max ) {
return $a - $max;
}
}
Hope it helps.
You can do this with code like
$range = array('from' => 3, 'to' => 13);
$dist = $range['to'] - $range['from'];
$a = 7;
$b = 14;
echo ($dist + ($a % $range['to'] - $b % $range['to'])) % $dist; // $a - $b
echo ($dist + ($a % $range['to'] + $b % $range['to'])) % $dist; // $a + $b
Modulo will do the trick as others have shown, but you must also account for the lower end of the range.
E.g. looping an arbitrary value within an hour range will work since it's zero-based. But if you want to loop a value within a month range you will get into trouble with the last day, because:
31 % 31 = 0
So you will loop to zero when you should remain on 31.
To deal with any range, you need to do this:
$min = 5;
$max = 15;
$value = 25; // The range is 11, so we want this turned into 14
$range = $max - $min + 1;
$value = (($value-$min) % $range) + $min;
To deal with values below minimum:
$range = $max - $min + 1;
$value = ($min - $value) % $range;
$value = $max - ($value - 1);

Find what 2 numbers add to something and multiply to something

Hey so I'm making a factoring program and I'm wondering if anyone can give me any ideas on an efficient way to find what two numbers multiple to a specified number, and also add to a specified number.
for example I may have
(a)(b) = 6
a + b = 5
So essentially i just need a way to find the a and b values. In this case they would be 2 and 3.
Can anyone give me any ideas on where to start? Negative numbers must also be considered for use.
There is no need to loop, just use simple math to solve this equation system:
a*b = i;
a+b = j;
a = j/b;
a = i-b;
j/b = i-b; so:
b + j/b + i = 0
b^2 + i*b + j = 0
From here, its a quadratic equation, and it's trivial to find b (just implement the quadratic equation formula) and from there get the value for a.
There you go:
function finder($add,$product)
{
$inside_root = $add*$add - 4*$product;
if($inside_root >=0)
{
$b = ($add + sqrt($inside_root))/2;
$a = $add - $b;
echo "$a+$b = $add and $a*$b=$product\n";
}else
{
echo "No real solution\n";
}
}
Real live action:
http://codepad.org/JBxMgHBd
Here is how I would do that:
$sum = 5;
$product = 6;
$found = FALSE;
for ($a = 1; $a < $sum; $a++) {
$b = $sum - $a;
if ($a * $b == $product) {
$found = TRUE;
break;
}
}
if ($found) {
echo "The answer is a = $a, b = $b.";
} else {
echo "There is no answer where a and b are both integers.";
}
Basically, start at $a = 1 and $b = $sum - $a, step through it one at a time since we know then that $a + $b == $sum is always true, and multiply $a and $b to see if they equal $product. If they do, that's the answer.
See it working
Whether that is the most efficient method is very much debatable.
With the multiplication, I recommend using the modulo operator (%) to determine which numbers divide evenly into the target number like:
$factors = array();
for($i = 0; $i < $target; $i++){
if($target % $i == 0){
$temp = array()
$a = $i;
$b = $target / $i;
$temp["a"] = $a;
$temp["b"] = $b;
$temp["index"] = $i;
array_push($factors, $temp);
}
}
This would leave you with an array of factors of the target number.
That's basically a set of 2 simultaneous equations:
x*y = a
X+y = b
(using the mathematical convention of x and y for the variables to solve and a and b for arbitrary constants).
But the solution involves a quadratic equation (because of the x*y), so depending on the actual values of a and b, there may not be a solution, or there may be multiple solutions.

Categories