Another FizzBuzz solution [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I was in a job interview and was asked to solve FizzBuzz with PHP.
Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.
I never heard of FizzBuzz before but here is how I solved it because I didn't know modulo or how to use it.:
for ($i = 1; $i <= 100; $i++){
if($i / 3 == round($i / 3) && $i / 5 == round($i / 5)){
echo $i . " is FizzBuzz<br />";
}
else if($i / 3 == round($i / 3)){
echo $i . " is Fizz<br />";
}
else if($i / 5 == round($i / 5)){
echo $i . " is Buzz<br />";
}
else {
echo $i."<br />";
}
}
I googled and didn't find any solution with round and that got me thinking that maybe there is something wrong with it, this is one of the solutions I found that is close to mine:
for ($i = 1; $i <= 100; $i++){
if($i % 3 == 0 && $i % 5 ==0){
echo "FizzBuzz<br />";
}
else if($i % 3 == 0){
echo "Fizz<br />";
}
else if($i % 5 == 0){
echo "Buzz<br />";
}
else {
echo $i."<br />";
}
}
My code is working fine but is there anything wrong with it that I don't see?

Actually they are testing how you will solve such simple task. It should be increadibly optimized, the code shouldbe clean and easy readable.
Your version of code is not good.
The version you've found in the internet is better, but it's not ideal from the point of the optimization.
Try to think how to get the goal with less actions.
Some tips:
do not use functions (such as range) for this task - it will only slow down the script execution time
use operator "for" for this task, do not use any other (while, do-while, foreach), because operator "for" the best fits in this case (you know how many iterations you need).
do not use round function, use modulus operator "%", because any function works slower than any operator
in the result you need to get code, in which the number of operations will be the least as possible (the number of "if" statements, the number of operators like "==" or "%"
Use 15 instead of % 3 && % 5 - less calculations - faster execution time.
My example of code:
for ($i = 1; $i <= 100; $i++) {
if ($i % 15 == 0) {
echo 'FizzBuzz<br>';
} elseif ($i % 3 == 0) {
echo 'Fizz<br>';
} elseif ($i % 5 == 0) {
echo 'Buzz<br>';
} else {
echo $i . '<br>';
}
}

Code style and lack of optimization gives impression of a newbie to the interviewer. My tips are:
Follow PSR-2
Never use else (restructure, use early returns/continues)
Always try to reduce the number of ifs (code complexity)
Use "identical" operators for comparison when dealing with integers and nulls (and any other type)
Do not use <br/> when HTML is never mentioned
Try to keep maintainability:
Extract match calculations in variables/functions, so they can be easily changed
Do not overcomplicate.
Try to optimize mathematically:
Use %15 instead of %3 and %5 check
You can also skip the above at all (check for %15), as you already have calculated that. Boolean operations are much faster.
Try not to calculate something twice.
IMHO, to follow all good practices your code should look like this:
for ($i = 1; $i <= 100; $i++) {
$isFizz = (0 === $i % 3);
$isBuzz = (0 === $i % 5);
if (!$isFizz && !$isBuzz) {
echo $i . PHP_EOL;
continue;
}
if ($isFizz) {
echo 'Fizz';
}
if ($isBuzz) {
echo 'Buzz';
}
echo PHP_EOL;
}
Test
There is yet another tricky solution
for ($i = 1; $i <= 100; $i++) {
switch ($i % 15) {
case 3:
case 6:
case 9:
echo 'Fizz';
break;
case 5:
case 10:
echo 'Buzz';
break;
case 0:
echo 'FizzBuzz';
break;
default:
echo $i;
break;
}
echo PHP_EOL;
}

if you read carefully it says "instead".
this is another short and clean solution of the FizzBuzz problem :
foreach (range(1, 100) as $number) {
if(0 !== $number % 3 && 0 !== $number % 5) {
echo $number.'<br>';
continue;
}
if(0 === $number % 3) {
echo 'Fizz';
}
if(0 === $number % 5) {
echo 'Buzz';
}
echo '<br>';
}
the output is :
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16

Related

Number counter game

Im trying to make a random number counter game that uses a for loop to print out 6 random numbers 1 - 6. I want to make it so the code can say how many times the number 6 shows in the loop.
At the moment I have the code it prints out for a loop of 6 random numbers but it only counts the numbers printed out.
For example
Welcome to the Dice Game!
How many sixes will you roll?
4 2 4 6 4 6
You rolled 2 six(es)!
<?php
echo"<h1>Welcome to the guess game thing guess how many 6s!</h1>";
$counter = 0;
for ($i=0; $i <=6;$i++) {
$randomNum = rand(1,6);
if ($randomNum <= 6) {
echo "<br> $randomNum";
$counter++;
}
else
{
echo"$randomNum <br>";
}
}
echo"<br>You rolled $counter sixes";
Some minor changes but you were almost there. Being consistent with your line breaks and verifying you check specifically for 6
$numberToMatch = 6;
for ($i = 0; $i <= 6; $i++) {
$randomNum = rand(1,6);
if ($randomNum == $numberToMatch) {
$counter++;
}
echo "$randomNum <br>";
}
You can do it like this:
$num = $_POST["num"];
for ($i=0; $i <=100;$i++) {
$randomNum = rand(1,10);
if ($randomNum == $num) {
echo $randomNum;
break;
}
echo $randomNum;
}
echo"<h2> there are $i</h2>";

PHP: Declaring if a value is odd or even from a random integer [duplicate]

This question already has answers here:
Test if number is odd or even
(20 answers)
Closed 5 years ago.
I don't know where I am going wrong with my code and I am asking for some guidance as I am new to PHP.
I am trying to do an If else statement that will display if the random integer is odd or even. When I run the code it keeps on showing 'Number is odd' or nothing and I am not sure why. Any guidance will be much appreciated.
$RandomValue = rand(0, 10);
$OddValues = (1 || 3 || 5 || 7 || 9);
$EvenValues = (0 || 2 || 4 || 6 || 8 || 10);
if($RandomValue == $OddValues) {
echo $RandomValue, ' Number is odd';
} else {
if($RandomValue == $EvenValues)
echo $RandomValue, ' Number is even';
}
There is a much easier way to do this. Use the modulo operator in php which is written as %. The modulo operator essentially returns 0 if there's no remainder and the remainder if there is. In this case, you're looking to just divide by 2 and see if anything remains, that's what modulo is doing here. So the only thing it's going to return is either 0 or 1.
$x = 3;
if($x % 2 == 0) { //number is even}
else { //number is odd }
Check it like
if ($RandomValue % 2 === 0) {
echo "$RandomValue is even";
} else {
echo "$RandomValue is odd";
}
For reference, see:
http://php.net/manual/en/language.operators.arithmetic.php
https://en.wikipedia.org/wiki/Modulo_operation
You can also check using the bitwise &
$is_odd = $x & 1;
Such as this
$nums = [1,2,3,4,5,6,7,8,9,10];
foreach( $nums as $x ){
$is_odd = $x & 1;
echo $is_odd ? 'ODD' : 'EVEN';
echo "\n";
}
Output
ODD
EVEN
ODD
EVEN
ODD
EVEN
ODD
EVEN
ODD
EVEN
You can test it here
http://sandbox.onlinephpfunctions.com/code/d47ab3970f24038afb28876b212a6f020eb0a0aa
And for a complete answer to your question
$RandomValue = rand(0, 10);
if($RandomValue & 1) {
echo $RandomValue. ' Number is odd';
} else {
echo $RandomValue. ' Number is even';
}
PS. you also have a comma and not a . here
echo $RandomValue, ' Number is odd';
http://sandbox.onlinephpfunctions.com/code/e2573a5dfe0e5aec6c0bfac3ce62c6788b070641
And indeed we can condense this a bit more into only 2 lines
$RandomValue = rand(0, 10);
echo $RandomValue. ' Number is '.($RandomValue & 1 ? 'even' : 'odd');
Oh and if you are not sure what the & "single and" is ( or bitwise in general ):
http://php.net/manual/en/language.operators.bitwise.php
Use Modulo.
if($RandomValue % 2 === 0){ echo $RandomValue, ' Number is even'; }
you can use ternary operator and do the test in one line :
function evenOrOdd($number)
{
return 0 === $number % 2 ? 'even' : 'odd';
}

Detect if input is a prime number in PHP - concerned with best practice code syntax [duplicate]

This question already has answers here:
A formula to find prime numbers in a loop
(22 answers)
Closed 7 years ago.
I'm teaching my wife to code, so we made a simple prime-number detector.
We came up with this, but I'm wondering if there's a better / neater way. I particularly don't like the 0/1 switch for displaying the end statement.
//get n from URL
$n = $_GET['n'];
$j=2;
$prime=1;
while ($j<=($n/2)){
if (is_int($n/$j)){ $prime=0;
break;
}
$j++;
}
if ($prime==1) {echo "Yes! $n is a prime number";}
else {echo "No, $n is not a prime number";}
As far as a 'neater' way to display the end statement, you could just tidy it up with:
echo ($prime) ? "Yes! $n is a prime number" : "No, $n is not a prime number";
Also for readability you could use boolean true/false instead of 1 and 0's but that's really just your preference.
There is always the neat and newbie friendly regular expressions way of finding prime numbers:
$n = $_GET['n'];
echo "$n is ", preg_match('/^1?$|^(11+?)\1+$/', str_repeat('1', $n))
? "not " : "", "a prime number", PHP_EOL;
No seriously, what I would suggest is that you tidy up your code a bit, so it gets easier to read:
Remove unnecessary parentheses
Rename $prime to $isPrime
Change $j++ into $j = $j + 1
Add a quick check on 0, 1 which are not prime numbers
Like so:
// Get parameter 'n' from URL
$n = $_GET['n'];
if ($n <= 1) {
$isPrime = false;
}
else {
$isPrime = true;
$j = 2;
while ($j <= $n / 2) {
if (is_int($n / $j)) {
$isPrime = false;
break;
}
$j = $j + 1;
}
}
if ($isPrime) {
echo "$n is a prime number";
}
else {
echo "$n is not a prime number";
}

Prime number loop stop at first found number [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hello i would like the loop below to generate a random prime number below 1000. But only generate 1 with the variable $i and the variable $finish should allow the while loop to stop after the first prime number is found and if the number is not prime it should generate a new $i variable randomly and check if its a prime number again until the first prime number is found.
<html>
<body>
<?php
$finish="a";
while($finish = "a") {
$i = (mt_rand(0,999));
$counter = 0;
for($j = 1; $j <= $i; $j++) { //all divisible factors
if($i % $j == 0) {
$counter++;
}
//prime requires 2 rules ( divisible by 1 and divisible by itself)
if($counter == 2){
print $i." is Prime <br/>";
$finish = "b";
}
}
}
?>
</body>
</html>
how can i modify this so that it will stop the code after the first prime number below 1000 is found?
The problem is $finish="a" - you are assigning the string a (which is truthy) to $finish. So this loop will run forever (as the condition is always true).
You are setting flags as string and ints while boolean here should suffice. In addition to that, once a divisor >= 2 is found you can stop the for() loop. If you introduce a helper function it becomes even more readable.
function isPrime($number) {
$max = $number;
for ($i=2; $i < $max; $i++) {
if ($number % $i == 0)
return false;
}
return true;
}
do {
$i = mt_rand(100, 9999);
} while ( ! isPrime($i) );
var_dump($i);
See it work here. I'm not too sure but sqrt($number) should suffice as $max and make the loop shorter -> the script faster.
To break out of your 2 loops when the condition is matched, you can use break 2:
if($counter == 2){
print $i." is Prime <br/>";
$finish = "b";
break 2;
}

resolving this simple php math

I am trying to get multiple number of 2 and 3 pls help. Thanks
for($i = 0; $i <30; $i++)
if($i % 2)
echo 'number is '. $i . ' is multiple of 2 <br/>';
elseif($i %3)
echo 'number is '. $i . 'is multiple of 3 <br/>';
else
echo 'number is '. $i . 'is multiple of some other number <br/>';
Try this:
if($i % 2 === 0)
...
elseif($i %3 === 0)
...
Basically if the modulo is 0 then that means the number is evenly divisible.
However, another problem with your logic is that a number may be divisible by both 2 and 3. You can fix this by extracting these out into separate if statements:
if($i %2 === 0) {
...
}
if($i %3 === 0) {
...
}
But that sort of breaks your last else since you cannot just fall though to it anymore. You could solve that by setting a variable to false at the top of your loop. Then if any of your if statements is triggered, set the variable to true. Finally, print the "not divisible" message at the end of each iteration if the variable is still false.
You want a NOT if(i%2) because it is a multiple if the remainder is zero.
Additionally if you're trying to find multiples of 30 you only need to loop up to 15. Or number/2.
for($i = 0; $i < 30; $i++)
{
if($i % 2 == 0)
echo 'number is '. $i . ' is multiple of 2 <br/>';
elseif($i % 3 == 0)
echo 'number is '. $i . 'is multiple of 3 <br/>';
else
echo 'number is '. $i . 'is multiple of some other number <br/>';
}
I would add one more condition before your if conditions
if($i%2 === 0 && $i%3 === 0) {
echo 'multiple of 2 and 3\n';
}
It may also be correct to use:
if ($i%6 === 0) {
....
}
for the above if condition.
Even better if you use a switch case block.

Categories