PHP Create a while-loop that subtracts? - php

I got this Exercise :
Create a while-loop that subtracts 5.23 from the number 526 until the number is between (not equal to) 41 and 51. Answer with the final result as a float, rounded to 2 decimals.
What I doing wrong ?
$number = 1;
$sum = 526;
while ($number > 41 && $number < 51)
{
$sum-=5.23;
$number++;
}

Your loop never actually runs as 1 is never > 41 && < 51
$sum = 526;
while (1)
{
$sum -= 5.23;
if ( $sum > 41 && $sum < 51 ) { break; }
}
$ANSWER = sprintf('%2.2f', $sum);
echo $ANSWER;

Related

Print triangular number patterns with loops and modulus calculation

I need to print a number pattern like this:
1
12
123
1234
2
23
234
2341
3
34
341
3412
4
41
412
4123
My code:
for($i=1; $i<=4; ++$i) {
for($j=1; $j<=$i; ++$j) {
echo $j;
}
echo ("<br/>");
}
for($i=2; $i<=4; ++$i) {
for($j=2; $j<=$i; ++$j) {
echo $j;
}
echo ("<br/>");
}
I don't know how to recycle to the first number after the max number is reached. Since my max number is 4, 1 should used instead of 5 (and 2 for 6 and 3 for 7).
You loop from 1 to 4, and subtract 4 if the value is bigger than 4.
This is for 2, 23, 234, 2341:
for ($i = 1; $i <= 4; $i++) {
for ($j = 1; $j <= $i; $j++) {
$value = $j + 1; // or +2, or +3
echo $value > 4 ? $value - 4 : $value;
}
echo "\n";
}
And this would generate all output within one big loop:
$max = 4;
for ($start = 0; $start < $max; $start++) {
for ($i = 1; $i <= $max; $i++) {
for ($j = 1; $j <= $i; $j++) {
$value = $j + $start;
echo $value > $max ? $value - $max : $value;
}
echo "\n";
}
}
Whenever you need circular array access, it is a good idea to implement a modulus calculation. To set this up, use a range between 0 and 3 instead of using 1 and 4. A modulus calculation can return a 0 result, so the formula must be prepared to handle this value. To adjust the value, just add 1 after the modulus calculation to generate numbers between 1 and 4.
Accumulate strings of numbers as desired and reset the string upon each start of the outer loop.
Below proves that you do not need three nested loops for this task.
Code: (Demo)
for ($i = 0; $i < 4; ++$i) {
for ($s = '', $j = 0; $j < 4; ++$j) {
$s .= ($i + $j) % 4 + 1;
echo $s . "\n";
}
}
Output:
1
12
123
1234
2
23
234
2341
3
34
341
3412
4
41
412
4123

Can someone help me return a value?

I have created a loop which returns a random number between two values. Cool.
But now I want the script to return the following value too: The number of unique numbers between two similar numbers.
Example:
4
5
8
22
45
3
85
44
4
55
15
23
As you see there is a double which is the four and there are 7 numbers inbetween. So I would like the script to echo these numbers two so in this case it should echo 7 but if there are more doubles in the list it should echo all the numbers between certain doubles.
This is what I have:
for ($x = 0; $x <= 100; $x++) {
$min=0;
$max=50;
echo rand($min,$max);
echo "<br>";
}
Can someone help me or guide me? I'm learning :)
Thanks!
So You need to seperate script for three parts:
getting randoms and save them to array (name it 'result'),
analyze them,
print (echo) results
Simply - instead of printing every step of loop, save them to array(), exit loop, analyze every item with other, example:
take i element of list
check is i+j element is the same
if is it the same - save j-i to second array() (name it 'ranges')
And after this, print two arrays (named by me as 'result' and 'ranges')
UPDATE:
Here's solution, hope You enjoy:
$result = array(); #variable is set as array object
$ranges = array(); #same
# 1st part - collecting random numbers
for ($x = 0; $x < 20; $x++)
{
$min=0;
$max=50;
$result[] = rand($min,$max); #here's putting random number to array
}
$result_size = count($result); #variable which is containg size of $result array
# 2nd part - getting ranges between values
for ($i = 0; $i < $result_size; $i++)
{
for ($j = 0; $j < $result_size; $j++)
{
if($i == $j) continue; # we don't want to compare numbers with itself,so miss it and continue
else if($result[$i] == $result[$j])
{
$range = $i - $j; # get range beetwen numbers
if($range > 0 ) # this is for miss double results like 14 and -14 for same comparing
{
$ranges[$result[$i]] = $range;
}
}
}
}
#3rd part - priting results
echo("RANDOM NUMBERS:<br>");
foreach($result as $number)
{
echo ("$number ");
}
echo("<br><br>RANGES BETWEEN SAME VALUES:<br>");
foreach($ranges as $number => $range)
{
echo ("For numbers: $number range is: $range<br>");
}
Here's sample of echo ($x is set as 20):
RANDOM NUMBERS:
6 40 6 29 43 32 17 44 48 21 40 2 33 47 42 3 22 26 39 46
RANGES BETWEEN SAME VALUES:
For numbers: 6 range is: 2
For numbers: 40 range is: 9
Here is your fish:
Put the rand into an array $list = array(); and $list[] = rand($min,$max); then process the array with two for loops.
$min=0;
$max=50;
$list = array();
for ($x = 0; $x <= 100; ++$x) {
$list[] = rand($min,$max);
}
print "<pre>";print_r($list);print "</pre>";
$ranges = array();
$count = count($list);
for ($i = 0; $i < $count; ++$i) {
$a = $list[$i];
for ($j = $i+1; $j < $count; ++$j) {
$b = $list[$j];
if($a == $b) {
$ranges[] = $j-$i;
}
}
}
print "<pre>";print_r($ranges);print "</pre>";

How to round up to the next even number?

I want to round up to the next even whole number, with php.
Example:
if 71 -> round up to 72
if 33.1 -> round up to 34
if 20.8 -> round up to 22
$num = ceil($input); // Round up decimals to an integer
if($num % 2 == 1) $num++; // If odd, add one
Test cases:
$tests = ['71' => '72', '33.1' => '34', '20.8' => '22'];
foreach($tests as $test => $expected) {
$num = ceil($test);
if($num % 2 == 1) $num++;
echo "Expected: $expected, Actual: $num\n";
}
Produces:
Expected: 72, Actual: 72
Expected: 34, Actual: 34
Expected: 22, Actual: 22
$num = ceil($input); // Round up Floats to an integer
$num += $num % 2; // add $num modulo 2 remainder (is 1 if odd, 0 if even)
More options:
$num += $num % 2; //next even
$num -= $num % 2; //prev even
$num += ($num + 1) % 2; //next odd
$num -= ($num + 1) % 2; //prev odd

how to find the sum of all the multiples of 3 or 5 below 1000 in php, issue?

i have an small issue with the way this problem is resolved.
some would say: println((0 /: ((0 until 1000).filter(x => x % 3 == 0 || x % 5 == 0))) (_+_)) is the solution witch adds to 233168
my way was to do:
$maxnumber = 1000;
for ($i = 3; $i < $maxnumber; $i += 3)
{
$t += $i;
echo $i.',';
}
echo '<br>';
for ($j = 5; $j < $maxnumber; $j += 5)
{
$d += $j;
echo $j.',';
}
echo '<br>';
echo $t;
echo '<br>';
echo $d;
echo '<br>';
echo $t+$d;
this will give me :
3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,60,63,66,69,72,75,78,81,84,87,90,93,96,99,102,105,108,111,114,117,120,123,126,129,132,135,138,141,144,147,150,153,156,159,162,165,168,171,174,177,180,183,186,189,192,195,198,201,204,207,210,213,216,219,222,225,228,231,234,237,240,243,246,249,252,255,258,261,264,267,270,273,276,279,282,285,288,291,294,297,300,303,306,309,312,315,318,321,324,327,330,333,336,339,342,345,348,351,354,357,360,363,366,369,372,375,378,381,384,387,390,393,396,399,402,405,408,411,414,417,420,423,426,429,432,435,438,441,444,447,450,453,456,459,462,465,468,471,474,477,480,483,486,489,492,495,498,501,504,507,510,513,516,519,522,525,528,531,534,537,540,543,546,549,552,555,558,561,564,567,570,573,576,579,582,585,588,591,594,597,600,603,606,609,612,615,618,621,624,627,630,633,636,639,642,645,648,651,654,657,660,663,666,669,672,675,678,681,684,687,690,693,696,699,702,705,708,711,714,717,720,723,726,729,732,735,738,741,744,747,750,753,756,759,762,765,768,771,774,777,780,783,786,789,792,795,798,801,804,807,810,813,816,819,822,825,828,831,834,837,840,843,846,849,852,855,858,861,864,867,870,873,876,879,882,885,888,891,894,897,900,903,906,909,912,915,918,921,924,927,930,933,936,939,942,945,948,951,954,957,960,963,966,969,972,975,978,981,984,987,990,993,996,999
5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100,105,110,115,120,125,130,135,140,145,150,155,160,165,170,175,180,185,190,195,200,205,210,215,220,225,230,235,240,245,250,255,260,265,270,275,280,285,290,295,300,305,310,315,320,325,330,335,340,345,350,355,360,365,370,375,380,385,390,395,400,405,410,415,420,425,430,435,440,445,450,455,460,465,470,475,480,485,490,495,500,505,510,515,520,525,530,535,540,545,550,555,560,565,570,575,580,585,590,595,600,605,610,615,620,625,630,635,640,645,650,655,660,665,670,675,680,685,690,695,700,705,710,715,720,725,730,735,740,745,750,755,760,765,770,775,780,785,790,795,800,805,810,815,820,825,830,835,840,845,850,855,860,865,870,875,880,885,890,895,900,905,910,915,920,925,930,935,940,945,950,955,960,965,970,975,980,985,990,995
$t - 166833
$d - 99500
and total:
266333
why am i wrong?
Some numbers are multiples of both 3 and 5. (Your algorithm adds these numbers to the total twice.)
Because 6 * 5 == 30 and 10 * 3 == 30, you're adding the some numbers up twice.
$sum = 0;
$i = 0;
foreach(range(0, 999) as $i) {
if($i % 3 == 0 || $i % 5 == 0) $sum += $i;
}
Because you double-count numbers that are multiple of both 3 and 5, i.e. multiples of 15.
You can account for this naively by subtracting all multiples of 15.
for ($j = 15; $j < $maxnumber; $j += 15)
{
$e += $j;
echo $j.',';
}
$total = $total - $d;
In your case, if it is 15, you will add the number twice.
Try this:
$t = 0;
$d = 0;
for ($i = 0; $i <= $maxnumber; $i++){
if ($i % 3 == 0)
$t+= $i;
else if ($i % 5 == 0)
$d += $i;
}
echo $t.'<br>'.$d;
I think that in your code, if a number is a multiple of 3 and 5, it is added twice. Take 15 for example. It's in your list of multiples of 3 and in the list of multiples of 5. Is this the behaviour you want?
One of the best approach to this solution (to achieve optimum time complexity), run an Arithmetic Progression series and find the number of terms in all series by using AP formula: T=a+(n-1)d, then find sum by : S=n/2[2*a+(n-1)d]
where : a=first term ,n=no. of term , d=common deference, T=nth term
The code solution below has been implemented to suit the question above - so the values 3 and 5 are hard-coded. However, the function can modified such that values are passed in as variable parameters.
function solution($number){
$val1 = 3;
$val2 = 5;
$common_term = $val1 * $val2;
$sum_of_terms1 = calculateSumofMulitples($val1,$number);
$sum_of_terms2 = calculateSumofMulitples($val2,$number);
$sum_of_cterms = calculateSumofMulitples($common_term,$number);
$final_result = $sum_of_terms1 + $sum_of_terms2 - $sum_of_cterms;
return $final_result;
}
function calculateSumofMulitples($val, $number)
{
//first, we begin by running an aithmetic prograssion for $val up to $number say N to get the no of terms [using T=a +(n-1)d]
$no_of_terms = (int) ($number / $val);
if($number % $val == 0) $no_of_terms = (int) ( ($number-1)/$val ); //since we are computing for a no of terms below N and not up to/exactly/up to N. if N divides val with no remainder, use no of terms = (N-1)/val
//second, we compute the sum of terms [using Sn = n/2[2a + (n-1)d]
$sum_of_terms = ($no_of_terms * 0.5) * ( (2*$val) + ($no_of_terms - 1) * $val );
// sum of multiples
return $sum_of_terms;
}
You can run a single loop checking whether the number is multiple of 3 OR 5:
for ($i = 0; $i < $maxnumber; $i++)
{
if($i%3 || $i%5){
$t += $i;
echo $i.',';}
}
I think the original code is not including numbers which are multiples of both 3 and 5 in the total: if the test for multiple of 3 matches, it takes that and goes on.
If you total the multiples of 15 up to 1000, you get 33165, which is exactly the difference between your total, 266333, and the original total, 233168.
Here's my solution to the question:
<?php
$sum = 0;
$arr = [];
for($i = 1; $i < 1000; $i++){
if((int)$i % 3 === 0 || (int)$i % 5 === 0)
{
$sum += $i;
array_push($arr,$i);
}
}
echo $sum;
echo '<br>';
print_r($arr);//Displays the values meeting the criteria as an array of values

checking if a number is divisible by 6 PHP

I want to check if a number is divisible by 6 and if not I need to increase it until it becomes divisible.
how can I do that ?
if ($number % 6 != 0) {
$number += 6 - ($number % 6);
}
The modulus operator gives the remainder of the division, so $number % 6 is the amount left over when dividing by 6. This will be faster than doing a loop and continually rechecking.
If decreasing is acceptable then this is even faster:
$number -= $number % 6;
if ($variable % 6 == 0) {
echo 'This number is divisible by 6.';
}:
Make divisible by 6:
$variable += (6 - ($variable % 6)) % 6; // faster than while for large divisors
$num += (6-$num%6)%6;
no need for a while loop! Modulo (%) returns the remainder of a division. IE 20%6 = 2. 6-2 = 4. 20+4 = 24. 24 is divisible by 6.
So you want the next multiple of 6, is that it?
You can divide your number by 6, then ceil it, and multiply it again:
$answer = ceil($foo / 6) * 6;
I see some of the other answers calling the modulo twice.
My preference is not to ask php to do the same thing more than once. For this reason, I cache the remainder.
Other devs may prefer to not generate the extra global variable or have other justifications for using modulo operator twice.
Code: (Demo)
$factor = 6;
for($x = 0; $x < 10; ++$x){ // battery of 10 tests
$number = rand( 0 , 100 );
echo "Number: $number Becomes: ";
if( $remainder = $number % $factor ) { // if not zero
$number += $factor - $remainder; // use cached $remainder instead of calculating again
}
echo "$number\n";
}
Possible Output:
Number: 80 Becomes: 84
Number: 57 Becomes: 60
Number: 94 Becomes: 96
Number: 48 Becomes: 48
Number: 80 Becomes: 84
Number: 36 Becomes: 36
Number: 17 Becomes: 18
Number: 41 Becomes: 42
Number: 3 Becomes: 6
Number: 64 Becomes: 66
Use the Mod % (modulus) operator
if ($x % 6 == 0) return 1;
function nearest_multiple_of_6($x) {
if ($x % 6 == 0) return $x;
return (($x / 6) + 1) * 6;
}
Simply run a while loop that will continue to loop (and increase the number) until the number is divisible by 6.
while ($number % 6 != 0) {
$number++;
}
Assuming $foo is an integer:
$answer = (int) (floor(($foo + 5) / 6) * 6)
For micro-optimisation freaks:
if ($num % 6 != 0)
$num += 6 - $num % 6;
More evaluations of %, but less branching/looping. :-P
Why don't you use the Modulus Operator?
Try this:
while ($s % 6 != 0) $s++;
Or is this what you meant?
<?
$s= <some_number>;
$k= $s % 6;
if($k !=0) $s=$s+6-$k;
?>
result = initial number + (6 - initial number % 6)

Categories