Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find if a number is divisible by 3 or 5 (FizzBuzz)

How do I change the output depending on whether or not it is divisible by 3 or 5? If it is divisible by 3, I want to show "rock" and if it's divisible by 5 I want to show "star" (similar to in FizzBuzz). If both, they'll see both.

Here's my code:

if (var n = Math.floor((Math.random() * 1000) + 1); {
  var output = "";
  if (n % 3 == 0)
    output += "Rock";
  if (n % 5 == 0)
    output += "star";
  prompt(output || n);
}

Why isn't my code working properly?

like image 911
Corey Blinks Avatar asked Oct 29 '25 17:10

Corey Blinks


2 Answers

var n = Math.floor((Math.random() * 1000) + 1);
if (n) {
  var output = "";
  if (n % 3 == 0)
    output += "Rock";
  if (n % 5 == 0)
    output += "star";
  prompt(output || n);
}

The var inside the if statement is a syntax error. My browser shows this error:

SyntaxError: expected expression, got keyword 'var'

So I think you should declare variable n before telling the if statement that var n is your comparison expression.

like image 191
Burning Crystals Avatar answered Nov 01 '25 07:11

Burning Crystals


let f = "fizz";
let b = "buzz";
for (let num = 1; num <=700 ; num++) {
    if (num% 3 === 0 && num % 5 ===0){
    console.log(num + f + b);
                }
    else if (num % 5 === 0){
    console.log(num+b);
                }
    else if (num % 3 === 0){
    console.log(num+f);
                }
    else {
    console.log(num);
                }
            }
like image 27
moran hagbi Avatar answered Nov 01 '25 08:11

moran hagbi