I can't figure this out. I want loopCheck to count by 5s all the way to 500. I know there's an easier way than writing all those numbers out.
for (i = 1; i <= 500; i++){
var loopCheck = i === 5 || i === 10 || i === 15 || i === 20 || i === 25;
if (loopCheck === true){
alert("if statement works!!!"):
}
}
For the sake of being different:
You can use the modulo % operator:
for (i = 1; i <= 500; i++) {
if (i % 5 === 0) { // if `i` is *perfectly* divisible by 5
// do something here
}
}
Just add 5 to i on each iteration:
for (i = 5; i <= 500; i += 5) {
// ...
}
i += 5 is shorthand for i = i + 5. Note that we start with i set to 5 here.
I agree with the simplicity Bens answer, as an alternative, you can use modulo:
for (var i = 1; i <= 500; i++){
if (i%5 === 0) {
console.log(i);
}
}
That maintains the "looping through every number" but with modulo you ask "when I divide the number by 5, what remainder do I have?" If its divisible by 5, you have a remainder of 0. :)
Related
Thinking it would be like
for number from range x,y
if number in ones or number in hundreds
print
else
??? I don't know what command to do the if statement.
You may try using the modulus operator here:
for (i=100; i <= 200; ++i) {
if (i % 10 == 2 || Math.floor(i / 10) % 10 == 3) {
console.log(i);
}
else {
// turned this off for demo purposes
// console.log("???");
}
}
for (let i = 100; i <= 200; i++) {
if (i % 10 === 2 || (i / 10) % 10 === 3) {
// do something
} else {
console.log('???')
}
}
You could store the tensDigit and onesDigit in variables and then check them in the if statement for better readabilty:
for (let num = 100; num <= 200; num++) {
const tensDigit = Math.floor((num % 100) / 10);
const onesDigit = num % 10;
if (tensDigit === 3 || onesDigit === 2) {
console.log(num);
}
}
your question is super ambiguous, please be more specific. That being said this function should do what you are asking.
function printIfDigitIsInPlace(INPUT, DIGIT, PLACE) {
const arr = Array.from(INPUT.toString());
if (arr[PLACE] === DIGIT.toString()) console.log(INPUT);
}
please I'm stuck in this question below since yesterday. Below is the question:
Write a program that uses console.log to print all the numbers from 1
to 100, with two exceptions. For numbers divisible by 3, print "Fizz"
instead of the number, and for numbers divisible by 5 (and not 3), print
"Buzz" instead.
When you have that working, modify your program to print "FizzBuzz",
for numbers that are divisible by both 3 and 5 (and still print "Fizz" or
"Buzz" for numbers divisible by only one of those).
I only got the first two conditions but not the the third. I don't know how to go about it anymore, I've tried many options. Below is my code:
<html>
<head/head>
<body>
<script type="text/javascript">
for (i = 1; i <= 100; i++)
if (i % 3 == 0) {
document.write("Fizz");
document.write("<br />");
} else if (i % 5 == 0 && i % 3 != 0) {
document.write("Buzz");
document.write("<br />");
} else if (i % 3 && 5 == 0 && i % 3 != 0 && i % 5 != 0) {
document.write("FizzBuzz");
document.write("<br />");
} else {
document.write(+i);
document.write("<br />");
}
</script>
</body>
</html>
Check the most specific (FizzBuzz) condition first.
function fizzBuzz() {
for(var i = 1; i <= 100; i++){
if(i % 5 === 0 && i % 3 === 0){
console.log('FizzBuzz');
} else if(i % 3 === 0){
console.log('Fizz');
} else if(i % 5 === 0){
console.log('Buzz');
} else {
console.log(i);
}
}
}
here is an updated version of your code, I keep it as you write it with some changes, I made it work without touch it's logic, you can see that the problem was in the first comparison and in the second "if else" (5 will never be equal to 0). you can optimize the code more than that, good luck.
<html>
<head/head>
<body>
<script type="text/javascript">
for (i = 1; i <= 100; i++)
if (i % 3 == 0 && i % 5 != 0) {
document.write("Fizz");
document.write("<br />");
} else if (i % 5 == 0 && i % 3 != 0) {
document.write("Buzz");
document.write("<br />");
} else if (i % 3 == 0 && i % 5 == 0) {
document.write("FizzBuzz");
document.write("<br />");
} else {
document.write(+i);
document.write("<br />");
}
</script>
</body>
</html>
Since everyone is contributing, I might as well give you an interesting solution:
var i = 101;
while(i --> 0){ // as i goes to 0... wat
var state = !!(i % 3) << 1 | !!(i % 5), // compute state?
output = ["FizzBuzz", "Fizz", "Buzz", i]; // hmm...
console.log(output[state]); // output correct string
}
1st - Instead of document.write use console.log like the question says
2nd - You have a syntax error in the head section. it should be <head></head>
3rd - for the 1st part of the question all you need is this:
for (i = 1; i <= 100; i++) {
// if i is divisible by 3
if (i % 3 == 0) {
console.log("Fizz");
}
// if i is divisible by 5 (no need to check for 3 again)
else if (i % 5 == 0) {
console.log("Buzz");
}
// else
else {
console.log(i);
}
}
4th - For the 2nd part you need to add an extra if on top of what you have already:
for (i = 1; i <= 100; i++) {
// if i is divisible by 3 and 5
if (i % 3 == 0 && i % 5 == 0) {
console.log("FizzBuzz");
}
// if i is divisible by 3
else if (i % 3 == 0) {
console.log("Fizz");
}
// if i is divisible by 5 (no need to check for 3 again)
else if (i % 5 == 0) {
console.log("Buzz");
}
// else
else {
console.log(i);
}
}
working fiddle: https://jsfiddle.net/tedmanowar/amapqcLL/
You can use a while loop, than use a nested if statements to check the conditions.
let number = 0;
while (number <= 100) {
if(number % 3 === 0 && number % 5 === 0){
console.log("FizzBuzz");
}else if(number % 3 === 0){
console.log("Fizz");
}else if(number % 5 === 0){
console.log("Buzz");
}else{
console.log(number);
}
number++;
}
This solution is the easiest and simplest. There are multiple ways to solve the question though.
for (n=1; n<=100; n++){
let output = "";
if(n % 3=== 0) output += "Fizz"
if(n % 5=== 0) output += "buzz"
console.log(output || n);
}
I don't recommend this answer - since it is very hard to maintain - but it does do it in very few lines. It also relies on the two numbers only having a common factor of 1.
for(let i=1; i<=100; i++) {
console.log(`${i%15?i%5?i%3?i:'Fizz':'Buzz':'FizzBuzz'}`)
}
This is using the ternary operator and backquote template strings.
You should just use a loop that starts at 1 and is less than 101 (so up to 100) and test for the %n === 0. In other words, make sure there is no remainder.
function startConsoleDemo(){
for(var i=1,r; i<101; i++){ // loop from 1 to 100
r = i; // default value of r
if(i % 3 === 0 && i % 5 === 0){ // if i/3 and 1/5 do not produce a remainder
r = 'FizzBuzz'; // reassign r
}
else if(i % 3 === 0){ // we knew i % 5 !== 0 so see if i/3 does not produce a remainder
r = 'Fizz'; // reassign r
}
else if(i % 5 === 0){ // we already knew i % 3 !== 0 - you know the drill
r = 'Buzz'; // reassign r
}
console.log(r); // console at each step of the loop no matter what
}
}
startConsoleDemo(); // without () you can use like a var then () later
I have a solution and I'm pretty sure it'll work for you.
for (let i = 1; i <= 100; i++) {
if (i % 3 === 0 && i % 5 === 0) {
document.write(`${i} FizzBuzz`);
} else if (i % 3 === 0 && i % 5 !== 0) {
document.write(`${i} Fizz`);
} else if (i % 5 === 0 && i % 3 !== 0) {
document.write(`${i} Buzz`);
} else {
document.write(`${i}`);
}
}
I'm trying to figure out how to count the number of "holes" in a number. That is, where 8 has two holes and 0, 4, 6, 9 have one hole and the rest have none.
For some reason I'm getting a return of undefined and I'm pulling my hair out over it. Am I missing something?
var numOfHoles = 0;
for (i = 0; i < num.length; i++) {
if (num === 8) {
numOfHoles += 2;
}
else if (num === 0 || num === 4 || num === 6 || num === 9) {
numOfHoles++;
}
else
numOfHoles;
}
console.log(numOfHoles);
}
Simply take the number, split it into an array of ints, and then use an arrow function as the argument for reduce to total the correlating value from the number to holes map.
function numHoles(n){
return (""+n).split('').reduce((t,i) => t+=+"1000101021"[i],0);
}
document.write(numHoles(48488621597));
I guess you are looking for something like this :
var num = [9,4,5];
var numOfHoles = 0;
for (i = 0; i < num.length; i++){
if (num[i] == 8)
{
numOfHoles += 2;
}
else if (num[i]== 0 || num[i]== 4 || num[i]== 6 || num[i]== 9)
{
numOfHoles++;
}
}
console.log(numOfHoles);
You had multiple little error.
First of all you didn't need else { numOfHoles } which dont mean anything.
And you need if you try to check every elements to use the indexation of the element so you need to use num[i].
Unless there was some code missing from the top when you copied this over, it looks like you need to either remove the trailing bracket or declare this as a function (see below).
Edit: This is a strange question. Firstly, the answers referencing using an index on num might not work as expected. The easiest, but possibly not best, answer would be to convert the number to a string, then index and compare to characters instead of numbers.
As everyone else has mentioned, it makes things much easier if you maintain proper code format :)
function countNumHoles(num) {
var numOfHoles = 0;
var numStr = num.toString();
for (i = 0; i < num.toString().length; i++) {
if (numStr[i] === '8') {
numOfHoles += 2;
} else if (numStr[i] === '0' || numStr[i] === '4' || numStr[i] === '6' || numStr[i] === '9') {
numOfHoles++;
}
}
console.log(numOfHoles);
}
The problem is that you idented wrongly the code, so it's harder to see the errors. The correct identation of your code goes like this:
var numOfHoles = 0;
for (i = 0; i < num.length; i++) {
if (num === 8) {
numOfHoles += 2;
} else if (num === 0 || num === 4 || num === 6 || num === 9) {
numOfHoles++;
} else
numOfHoles;
console.log(numOfHoles);
}
So now with the correct identation you can easily see that else numOfHoles; isn't needed, num ins't defined and length is for string or arrays. Also console.log is better outside the loop in order to run only once. Here is a functional version:
var numOfHoles = 0;
limit = 5;
for (num = 0; num <= limit; num++) {
if (num === 8) {
numOfHoles += 2;
} else if (num === 0 || num === 4 || num === 6 || num === 9)
numOfHoles++;
}
console.log(numOfHoles);
Considering all the answers on top, you have some mistakes with braces. But you are counting num of holes in array, but you don't have indexes. Here is my test snippet. And it has nothing to do with empty numOfHoles. But i still recommend to remove it.
var numOfHoles = 0;
var num = [4,0,9,8,5,5,5];
for (i = 0; i < num.length; i++) {
if (num[i] === 8) {
numOfHoles += 2;
}
else if (num[i] === 0 || num[i] === 4 || num[i] === 6 || num[i] === 9) {
numOfHoles++;
}
else
numOfHoles;
}
console.log(numOfHoles);
It's kind of hard to answer. You used the length property in the variable "num". But strictly used the comparison. The rule if always be false, considering that (string "8" !== 8). This type of comparison requires that the variables have the same type.In this case or you use an integer or an Array and uses the variable i to access your elements in the loop for
Solution, or you comes in as a string and uses the following system [if (num === "8")], or working on becoming a int, or work with an array (recommended). To know the best solution we needed to see more of the code.
Your code should stay that way. Of course, if you need something more specific, let us know
var num = [0,2,8,5];
var numOfHoles = 0;
for (i = 0; i < num.length; i++){
if (num[i] == 8)
{
numOfHoles += 2;
}
else if (num[i]== 0 || num[i]== 4 || num[i]== 6 || num[i]== 9)
{
numOfHoles++;
}
}
console.log(numOfHoles);
Write a javascript program that displays the numbers from 10 to 100. But for multiples of 4 print "Penny" instead of the number and for multiples of 6 print "Leonard". For numbers which are multiples of both 4 and 6 print "Bazzinga"
I know how to do two parts struggling to print 6 and 4;
function baZzinga (number) {
for (var number = 10; number <= 101; number++)
if(number % 4 == 0) {
console.log("penny");
}
else if (number % 6 == 0) {
console.log("Leonard");
} else if ( not sure what goes here) {
help help help
} else {
console.log(number");
}
You want the and condition first. Try this
var result = document.getElementById("result");
function baZzinga (number) {
for (var number = 10; number <= 101; number++) {
if (number % 4 == 0 && number % 6 == 0) {
result.innerHTML += "Bazinga";
}
else if(number % 4 == 0) {
result.innerHTML += "penny";
}
else if (number % 6 == 0) {
result.innerHTML += "Leonard";
}
else {
result.innerHTML += number;
}
}
}
baZzinga()
<p id="result"></p>
I changed console.log to result.innerHTML because I wanted to demonstrate it in a snippet.
I have a few comments on your code -- constructive criticism, I hope! First, you don't need the number parameter in your bazzinga function. Next, the indentation of the code you posted makes it hard to read. Finally, you should almost always use === instead of ==. The === tests for strict equality, whereas == tries to do some type conversions first (and can therefore produce unexpected results). See the official docs.
To answer you question: check for divisibility by 6 AND 8 first. That way, it will override the individual cases. I believe you want something like this:
function bazzinga() {
for (var number = 10; number <= 100; number++) {
if (number % 4 === 0 && number % 6 === 0) {
console.log("Bazzinga");
} else if (number % 4 === 0) {
console.log("Penny");
} else if (number % 6 === 0) {
console.log("Leonard");
}
}
}
Here is a solution using the format you posted:
for (var number = 10; number <= 100; number++) {
if(number % 4 === 0 && number % 6 === 0){
console.log("bazzinga");
} else if(number % 4 === 0) {
console.log("penny");
} else if (number % 6 === 0) {
console.log("Leonard");
} else {
console.log(number);
}
}
Or use the ternary operator to be even more succinct!
for (var i = 10; i <= 100; i++){
var penny = i % 4 === 0;
var leonard = i % 6 === 0;
console.log(penny ? (leonard ? "bazzinga" : "penny"): leonard ? "leonard" : i);
}
function process_num(num) {
return num % 4 == 0 ? num % 6 == 0 ? "Bazzinga" : "Penny" : num % 6 == 0 ? "Leonard" : num;
}
for (x = 10; x <= 100; x++) { console.log( x + ': is ', process_num(x)) }
Nested Ternary operator for conciseness
If it passes outer ternary test it is divisible by 4:
Enter into nested termary one to test if num is also divisible by 6 for the BaZzinga prize!!
If it fails the BaZzinga challenge, we know it previously passed the divisible by 4 test so print "penny"
Failing the outer ternary condition, we know it's not divisible by 4:
Enter nested ternary two to consider if divisible by 6. If so print "Leonard".
If not it's failed both the outer (div by 4) and inner (div by 6) so return the number unchanged.
Now that the logic is contained in the function, we can just create a for loop to iterate over the required numbers printing out the correct values.
It has to be with just functions, variables, loops, etc (Basic stuff). I'm having trouble coming up with the code from scratch from what I've I learned so far(Should be able to do it). Makes me really mad :/. If you could give me step by step to make sure I understand I'd really really appreciated. Thanks a bunch in advanced.
How could I get the same result with a simpler code than this one:
var primes=4;
for (var counter = 2; counter <= 100; counter = counter + 1)
{
var isPrime = 0;
if(isPrime === 0){
if(counter === 2){console.log(counter);}
else if(counter === 3){console.log(counter);}
else if(counter === 5){console.log(counter);}
else if(counter === 7){console.log(counter);}
else if(counter % 2 === 0){isPrime=0;}
else if(counter % 3 === 0){isPrime=0;}
else if(counter % 5 === 0){isPrime=0;}
else if(counter % 7 === 0){isPrime=0;}
else {
console.log(counter);
primes = primes + 1;
}
}
}
console.log("Counted: "+primes+" primes");
I'm feeling naughty today so:
function printPrimesBetweenTwoAndOneHundredSimply(){
var primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97],
i,
arrayLength = primes.length;
for(i = 0; i < arrayLength; i++){
console.log(primes[i]);
}
console.log("Counted: " + arrayLength + " primes");
}
First, you really don't need to use === for this. The standard == will suffice. Second, you can make all of those lines that are the same thing, except for a single digit into one line:
var primes=4;
for (var counter = 2; counter <= 100; counter = counter + 1)
{
var isPrime = 0;
if(isPrime == 0){
if(counter == 2 || counter == 3 ||counter == 5 || counter == 7)console.log(counter);
else if(counter % 2 == 0 || counter % 3 == 0 || counter % 5 == 0 || counter % 7 == 0)isPrime=0;
else {
console.log(counter);
primes = primes + 1;
}
}
}
console.log("Counted: "+primes+" primes");
You'll also notice that the {} was removed on a few lines. This is because a single line of code following an if (among others) is always considered nested.
Next, we can change your primes = primes + 1; to this: primes++; which just tells primes to increment itself by one. The same can be done for your counter. We also know that isPrime equals "0" because you set it to that a second ago, so we no longer need that if statement:
var primes=4;
for (var counter = 2; counter <= 100; counter++)
{
var isPrime = 0;
if(counter == 2 || counter == 3 ||counter == 5 || counter == 7)console.log(counter);
else if(counter % 2 == 0 || counter % 3 == 0 || counter % 5 == 0 || counter % 7 == 0)isPrime=0;
else {
console.log(counter);
primes++;
}
}
console.log("Counted: "+primes+" primes");
Next, we can do a negative check (!= instead of ==) on the values and combine your else if with your else. Since we're doing a negative check (for this case) we have to switch the ORs (||) to ANDs (&&):
var primes=4;
for (var counter = 2; counter <= 100; counter++)
{
if(counter == 2 || counter == 3 ||counter == 5 || counter == 7)console.log(counter);
else if(counter % 2 != 0 && counter % 3 != 0 && counter % 5 != 0 && counter % 7 != 0) {
console.log(counter);
primes++;
}
}
console.log("Counted: "+primes+" primes");
There are many other ways to write it, but I felt it more beneficial to you to use what you started with and shorten it from there.
This finds all prime numbers between 2 and 100:
var primes=0;
var isprime = true;
for (var counter = 2; counter <= 100; counter = counter + 1)
{
// For now, we believe that it is a prime
isprime = true;
var limit = Math.round(Math.sqrt(counter)); // See comment from #AresAvatar, below
// We try to find a number between 2 and limit that gives us a reminder of 0
for (var mod = 2; mod <= limit; mod++) {
// If we find one, we know it's not a prime
if (counter%mod == 0) {
isprime = false;
break; // Break out of the inner for loop
}
}
if (isprime) {
console.log(counter, limit);
primes = primes + 1;
}
}
console.log("Counted: "+primes+" primes");
Of course "simpler" is not defined. :-)
The following can be made much shorter, but has a bit of robustness built in.
// Get primes from 0 to n.
// n must be < 2^53
function primeSieve(n) {
n = Number(n);
if (n > Math.pow(2, 53) || isNaN(n) || n < 1) {
return;
}
var primes = [];
var notPrimes = {};
var num;
for (var i=2; i<n; i++) {
for (var j=2; j<n/2; j++) {
num = i*j;
notPrimes[num] = num;
}
if (!(i in notPrimes)) {
primes.push(i);
}
}
return primes
}
So if you want less code:
// Get primes from 0 to n.
// n must be < 2^53
function primeSieve2(n) {
var primes = [], notPrimes = {};
for (var i=2; i<n; i++) {
for (var j=2; j<n/2; j++)
notPrimes[i*j] = i*j;
i in notPrimes? 0 : primes.push(i);
}
return primes
}
This is pretty simple (I mean, short):
console.log(2); console.log(3);
var m5=25, m7=49, i=5, d=2, c=2;
for( ; i<100; i+=d, d=6-d )
{
if( i!=m5 && i!=m7) { console.log(i); c+=1; }
if( m5 <= i ) m5+=10;
if( m7 <= i ) m7+=14;
}
c
It is an "unrolled" sieve of Eratosthenes with 2-3-wheel factorization.
On the one hand, we enumerate all the numbers below 100 (and bigger than 3) that are coprime with 2 and 3, as partial sums of 5+2+4+2+4+... , so that there are no multiples of 2 and 3 among thus enumerated numbers.
On the other hand, we discard from among them all the multiples of 5 and 7, by enumerating them as partial sums of 25+10+10+10+... and 49+14+14+14+... . Multiples of 2 and 3 are not there in the first place, and the first multiple of 11 that needs to be discarded by the sieve of Eratosthenes is 121.
This will be simpler for your Question....
for (int i = 2; i < 100; i++) {
int j = 0;
for (j = 2; j < i; j++)
if ((i % j) == 0)break;
if (i == j)
System.out.print(" " + i);}