Modulo in If statement being treated as statement - javascript

I am trying to write a javascript program that will count to 100, however, for every number divisible by 3, it will instead say 'divisible by 3' instead of displaying number
I'm using modulo to find out which numbers are divisible by 3 but my if statement is being treated as a statement rather then a conditional.
https://jsfiddle.net/gyoyfv7L/
My Code
var i = 1;
while (i < 101){
if(i % 3 = 0){
$("#main").append("divisible by 3");
}
else{
$("#main").append(i + '<br />');
}
i++;
}

= is for assignment. You want == or === for equality checking.
if(i % 3 == 0){
// ------^^
or
if(i % 3 === 0){
// ------^^^
== is "loose" in that it does type coercion using JavaScript's (sometimes surprising) rules. === is "strict" in that it will always be false when comparing values of different types.
Side note: When you have a loop consisting of an initialization of a control variable, a test of that variable, and an unconditional update of that variable at the end, it's better to use the idiomatic loop construct for that (for) rather than while:
for (var i = 1; i < 101; i++) {
if(i % 3 == 0){
$("#main").append("divisible by 3");
}
else{
$("#main").append(i + '<br />');
}
}

Related

Why code works when I write myArray[i] and not when I save myArray[i] in a variable?

I want to populate an empty array with the classical fizzbuzz game (numbers from 1 to 100, when a number is divisible by 3 print 'Fizz, divisible by 5 print 'Buzz', divisible by both 3 and 5 print 'Fizzbuzz'). The problem is, when I write code like in the first portion of code below saving my array[i] in a more convenient variable my if-else if statement doesn't work, only normal numbers are printed; but when I use array[i] instead of a variable everything works fine, as you can see in the second portion of code, where 'Fizz', 'Buzz', 'FizzBuzz' overwrite the normal numbers. They should be the same thing right?
First portion of code with a variable instead of array[i]
var numberArray = [];
var number = 0
for (var i = 0; i < 100; i++) {
number += 1;
thisNumber = numberArray[i];
numberArray.push(number);
if (number %3 ==0 && number %5 ==0) {
thisNumber = 'FizzBuzz';
} else if ( number %3 ==0 ) {
thisNumber = 'Fizz';
} else if ( number %3 ==0 ) {
thisNumber = 'Buzz';
}
}
console.log(numberArray);
Second portion of code with array[i] instead of a variable
var numberArray = [];
var number = 0
for (var i = 0; i < 100; i++) {
number += 1;
numberArray.push(number);
if (number %3 ==0 && number %5 ==0) {
numberArray[i] = 'FizzBuzz';
} else if ( number %3 ==0 ) {
numberArray[i] = 'Fizz';
} else if ( number %3 ==0 ) {
numberArray[i] = 'Buzz';
}
}
console.log(numberArray);
Reassigning a variable, by itself, never has any side effects (except in the most rare situations which aren't worth worrying about). Doing thisNumber = 'FizzBuzz'; does not change anything about how thisNumber may have happened to be used in the past.
Push after assigning to thisNumber. You also want to push thisNumber, not number.
You also need to change the final % 3 to % 5 - you're currently testing % 3 twice.
var numberArray = [];
for (var i = 0; i < 100; i++) {
let thisNumber = i;
if (i % 3 == 0 && i % 5 == 0) {
thisNumber = 'FizzBuzz';
} else if (i % 3 == 0) {
thisNumber = 'Fizz';
} else if (i % 5 == 0) {
thisNumber = 'Buzz';
}
numberArray.push(thisNumber);
}
console.log(numberArray);
In JavaScript a variable is just a reference to an object and an assignment changes where it points to. In
thisNumber = 'FizzBuzz';
you create a new string object and reference it with thisNumber. In
numberArray[i] = 'FizzBuzz';
you modify the i-th element of the array numberArray.
You can't create a reference to an array element and modify it with an assignment. That's not possible in JavaScript.

What is the time complexity of my code?

So I just started studying the Big O notation on my own. I thought I had understood the basics till I wrote a function to check for prime numbers and tried to figure out its time complexity. Here's the code:
function isPrime(num){
if (num === 1 || num%1 !== 0){ //Checks if num is 1 or decimal
return false;
}
else{
for (var i = 2; i < num; i++) {
if (num%i === 0 && i!== 1){ //Checks if any numbers from 2 to are divisible by num
return false
}
}
}
return true;
}
console.log(isPrime(6));
First thing that confused me is whether multiple conditions inside an if statement make any difference or it is just counted once? And then notice I have three return statements. Does that mean I have to include that last line of code where I pass a number to the function to evaluate its time-complexity? Or can I do it without a passed value and calculate for different cases?
function isPrime(n){
if (n === 1 || n%1 !== 0){ //Checks if num is 1 or decimal
return false;
}
for (var i = 2; i < n; i++) {
if (n%i === 0){
return false
}
}
return true;
}
I have made some small refactoring which doesn't change the complexity but makes the code more readable for struggling with Big-O.
So for n > 1, n : orime, the number of operations is:
So the complexity of your algorithm is O(n).

'for' loop and modulo

I've just started to learn JS and I'm having a bit of trouble understanding the basics behind the 'for' loop.
Example:
for (var number = 3; number % 7 == 0; number++)
Why doesn't it make sense? Why do I have to write it down like that:
for (var number = 3; ; number++) {
if (number % 7 == 0)
break;
}
Thank you for help!
You've inverted the condition. The middle part of a for loop tells you what must be true for the loop to continue. Your second version uses the same condition to decide when to stop.
for (A; B; C) { ... }
can be (mostly) rewritten as
A;
while (B) {
...
C;
}
(The difference is that continue in a for loop will still execute the C part.)
Initially your number is 3. Then we do the equivalent of while (number % 7 == 0) { ... }, but that condition fails (3 % 7 is 3, not 0), so the loop never runs.
You probably wanted
for (var number = 3; number % 7 != 0; number++)

I just want to call some loop when give the condition. but it was error

var game1 = prompt("Welcome to FuzzBUzz", "Let's try now GO");
for (var i= 1; i<21; i++){
if(i / 3){
console.log("Fizz");
}
else if (i/ 5){
console.log("Buzz");
}
else if ((i / 3) && (i / 5)){
console.log("FizzBuzz");
}
else{
console.log("choose what you want");
}
};
Your if statements are not conditional. You are just dividing i by a number. If you want to check if it's divisible, use the modulus and check for 0.
if(i%3 == 0){ //if i can be divided evenly by 3, then do something
do something
}
Conditions in if statements need to evaluate to a result which tells the if statement whether or not to execute the block; if the condition holds true the block is executed and vice versa. Change your condition statements to be statements which can be evaluated using comparison operators like: ==, !=, >, >= and you will be successful.

Using conditionals inside a loop

I am trying to achieve a check with the if...else statement that only squares the odd numbers between 100 and 150, otherwise the number is just printed.
How can I revise my if statement to achieve this please? An educated guess is that an operator or combination of operators are used.
for (i=100; i<=150; i++)
{
if (i === 0)
{
console.log(i * i);
}
else
{
console.log(i);
}
}
The operator you are looking for is %:
for(i = 100; i <= 150; i++) {
if(i % 2 === 1) { // It's odd
console.log(i * i);
} else {
console.log(i);
}
}
a % b is basically the remainder obtained when a is divided by b. It's called the modulus operator.
Two words: Modulus Division
A nice reference
if ( i % 2 === 0) {
console.log(i)
} else {
console.log(i * i)
}
Squares odd numbers.

Categories

Resources