Fizz Buzz return value javascript - javascript

I'm having an assignment where I have to do the FizzBuzz game in Javascript.
The problem is my loop stops after the first iteration and only return the first value (4). I may be blind to my code but I can't find where the error(s) is.
If you could please push me in the right direction I'd be happy. Thanks in advance. Regards, Thomas.
function fizzBuzz(start, stop) {
for(var i = start; i <= stop; i++) {
if (i % 3 == 0) {
return "fizz";
}else if( i % 5 == 0) {
return "buzz";
}else if(i % 15 == 0) {
return "fizz buzz";
}else {
return i;
}
}
}
ANSWER = (fizzBuzz(4, 22));
New code:
function fizzBuzz(start, stop) {
for(var i = start; i <= stop; i++) {
if (i % 3 == 0 && i % 5 == 0) {
document.write ("Fizz Buzz");
}else if(i % 3 == 0) {
document.write ("Fizz");
}else if(i % 5 == 0) {
document.write ("Buzz");
}else {
document.write(i);
}
}
}
ANSWER = (fizzBuzz(4, 22));
It returns: Answer = undefined

When your code encounters the return statement, the value given is returned from the whole function. This stops the for loop from iterating any further.
These are the questions you'll need to ask yourself:
What do you want to the fizzBuzz function to do? Should it print the text somewhere, or should it return a value?
If fizzBuzz should return a value, what would you expect that it returns? One line of text? Multiple lines of text all at once?

Whatever branch is taken within your for loop, there is always a return which exits the funtion with a return value. So, when you start with 4, the program enters the else branch and returns 4.
What you want is to print the value instead of returning from the function.
Also, I can see a logical error in the code. Assume i is 15, which is divisible by 3 and 5. Your program will go into the i % 3 branch and return "fizz" instead of "fizz buzz". You may want to change your if statements and/or work with string concatenation.
Hope I could help. ;)

One of the best solution in javascript to the fizzbuzz problem
const fizzbuzz = (start, stop) => {
const arr = [];
let str;
for(let i=start; i<=stop; i++) {
str = "";
if(i%3===0) {
str = "fizz";
}
if(i%5===0) {
str += "buzz";
}
arr.push(str||i);
}
return arr;
}
console.log(fizzbuzz(0, 105));

Related

Fizzbuzz function logic not working: Output order is incorrect and logic doesn't make sense

I'm creating a simple Javascript Function that should write the numbers from 1 to n. For any multiplier of 3, it outputs "Fizz", instead of multiplers of 5 you output "Buzz", and if they happen at the same time, you should use "FizzBuzz". The output of the function should be a mixed array of numbers and strings.
My current code is outputting the array order and expected values incorrectly.
function fizzbuzz (n) {
let arr = [];
for (let i = 0; i < n; i++){
//if i is a multiple of 3 then Fizz
if(i % 3 === 0) {
arr.push("Fizz");
}
//if i is a multiple of 5 then Buz
if(i % 5 == 0) {
arr.push("Buzz");
}
//if both then FizzBuzz
if(i % 3 === 0 && i % 5 === 0) {
arr.push("FizzBuzz");
}
else {
arr.push(i);
}
}
return arr;
}
When fizzbuzz(7) is entered, I expect the output to look like this:
[0, 1, 2, "Fizz", 4, "Buzz", "Fizz", 7];
Instead, it's this:
["Fizz","Buzz","FizzBuzz",1,2,"Fizz",3,4,"Buzz",5,"Fizz",6]
Could someone enlighten me to the fault in my logic? This should be more straightforward than I had originally thought.
You have three different if statements there, the last one having an else clause, instead of one continuous if statement with several else if clauses. Note that for this to work properly you need to first test the "FizzBuzz" condition:
function fizzbuzz (n) {
let arr = [];
for (let i = 0; i < n; i++){
//if both then FizzBuzz
if(i % 3 === 0 && i % 5 === 0) {
arr.push("FizzBuzz");
}
//if i is a multiple of 3 then Fizz
else if(i % 3 === 0) { // Changed to an else-if
arr.push("Fizz");
}
//if i is a multiple of 5 then Buz
else if(i % 5 == 0) { // Changed to an else-if
arr.push("Buzz");
}
else {
arr.push(i);
}
}
return arr;
}
Quick note regarding the expected output - 0 is divisible by 3 and 5 (and other other integer, for that matter), so the first element of the array should be "FizzBuzz"

Why does the 'if' condition here works?

The code here check for prime numbers from 2 to n:
<script>
function showPrimes(n) {
for (let i = 2; i < n; i++) {
if (!isPrime(i)) continue;
alert(i); // a prime
}
}
function isPrime(n) {
for (let i = 2; i < n; i++) {
if ( n % i == 0) return false;
}
return true;
}
</script>
But I don't understand why it works for number 2 and return false when both n and i equal to 2 while it doesn't happen with other prime numbers. I am new to javascript(and programming in general) and from what I understood this code take the i from the first iteration in the first loop(on the "showPrimes" function) and put it on "isPrime" function as a parameter and in that function it becomes the "n" in the 'if' condition and it checks if there is a remainder when it gets divided by the i from the loop of "isPrime" so (n % i == 0) should be (2 % 2 == 0) in the first iteration, Is that right? if so why does it works just like it work for other prime numbers which clearly become false unlike (2 % 2 == 0) which is true...
What I am missing here?. Sorry if this is an obvious/stupid question, it is the first time I am learning anything related to programming.
function isPrime(n) {
for (let i = 2; i < n; i++) {
When n=2; i=2; The above loop will not be entered.

How to use continue in a loop to change a value

I am trying to have a loop that gives me values from 1 to 30. However every number divisible by 10 I want to hard code the value to the corresponding word. Example would be value 10 = "Ten", 20 = "Twenty" and so on.
I tried to do this with 'continue', however my displayed results do not go pass "Ten".
for (i = 0; i <= 30; i++) {
if (i == 10) {
i = "Ten";
continue;
} if (i == 20) {
i = "Twenty";
continue;
}
console.log(i);
}
Results
Am I going on about it the right way? Could you please offer some hints so I can figure this out. Thank you,
I tried this initially. But didn't work.
for (i = 0; i <= 30; i++) {
if (i == 10) {
i = "Ten";
} if (i == 20) {
i = "Twenty";
}
console.log(i);
}
Just get rid of the continue statements. They cause the loop to immediately skip to the end and start another iteration. Thus, your console output statement is skipped. Also, you don't want to touch the loop variable, and it wouldn't hurt to have an else. Something like this:
var result;
for (i = 0; i <= 30; i++) {
if (i == 10) {
result = "Ten";
} else if (i == 20) {
result = "Twenty";
} else {
result = i;
}
console.log(result);
}
Or you could just log the desired output directly in each branch of the if/else chain:
for (i = 0; i <= 30; i++) {
if (i == 10) {
console.log("Ten");
} else if (i == 20) {
console.log("Twenty");
} else {
console.log(i);
}
}
I dont think you can change i and expect it to work as usual. hence as soon as you change the value to "TEN", the loop terminates..!!!!
When the counter i gets to ten, you are replacing it with a string, so when the control flow reaches the i++ part, your loop fails. What you should do is assign the value to be printed to another variable that is only used inside the body of the loop.

Euler #3 javascript error

I know this may get downvoted but I've been really frustrated for 24 hours and looking at other Euler 3 threads hasn't helped me solve this. Can someone help with my code? I think I'm very close.
function is_prime(num) {
if (isNaN(num)) return false;
for (i=2; i<=Math.sqrt(num); i++) {
if (num % i === 0) {
return false;
}
else {
return true;
}
}
}
// This above part CORRECTLY finds whether a number is prime or not. Problem lies with below part.
var holder = 0;
function getBiggestPrime (end) {
for (i=2; i<=Math.sqrt(end); i++) {
while (is_prime(i) && (end%i===0))
holder = i;
return holder;
}
}
getBiggestPrime(13195);
console.log(holder);
The first method is not correct. The corrected version will be:
<script>
function is_prime(num) {
if (isNaN(num)) return false;
for (var i=2; i<=Math.sqrt(num); i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
//Same problem with the second method - the return should be after the for-loop ends (also, change the while to if):
function getBiggestPrime (end) {
var holder = end;
for (var i=2; i<=Math.sqrt(end)+1; i++) {
if (is_prime(i) && (end%i===0))
holder = i;
}
return holder;
}
A link to the demo.
About the second part (if I understand correctly what you're looking for) you should start from:
i = Math.sqrt(end) and go down with i-- until you find the biggest prime.

Javascript prime number error?

Could someone please help me find the error in this code? I'm reading through what I came up with and it logically makes sense to me each step of the way, but it's not producing the desired result. At the end I test calling the function with 6.
function is_prime(num) {
if (isNaN(num)) return false;
var numFactors = 0;
for (i=1; i<=num; i++) {
if (num % i === 0) {
numFactors += 1;
}
return numFactors;
}
if (numFactors === 2) {
return true;
}
else {
return false;
}
}
console.log(is_prime(6));
You are returning the function from inside the forloop.
So it never hits the other statements
Check Fiddle
I believe the problem you are having is that you are potentially returning your numFactors too early:
for (i=1; i<=num; i++) {
if (num % i === 0) {
numFactors += 1;
}
return numFactors;
}
Here, you are returning the numFactors at the end of your first loop, so it never actually finishes the full test.
Counting factors is not a right approach -
use this -
function is_prime(num) {
if (isNaN(num)) return false;
var k = Math.sqrt(num);
for (i=2; i<=k; i++) {
if(num%i===0)return false;
}
return false;
}
console.log(is_prime(6));
As you are stepping through all numbers from 1 to num for factrorization you might as well pick them up as factors and get a bit more out of your function:
function fact(num) {
if (isNaN(num)) return false;
var Factors=[];
for (i=1; i<=num; i++) {
if (num % i == 0) Factors.push(i)
}
return Factors
}
console.log('factors: '+fact(27));
console.log('is prime: '+fact(27).length===2);

Categories

Resources