I'm looking to answer the question, but most important to understand where I did it wrong and why. In a certain way to learn how to do it.
So, the question is:
We've already declared a variable for you in the editor called number to which the value 42 was assigned.
Use a for loop to go through all numbers from number up to 50 (both inclusive), and check if they are multiples of 3. If they are, print them.
And I got to a point that I print to the console and I get the answer I want: 42, 45, 48.
But the console still gives me an error:
Remember the remainder operator? It might be of help to check if a number is a multiple of 3.
This is my code:
var number = 42;
var dividedbyThree = [];
for (var number = 42; number <= 50; number++) {
if (number % 3 == dividedbyThree) {
console.log(number);
}
}
What am I doing wrong?
Just replace
if (number % 3 == dividedbyThree)
with
if (number % 3 === 0)
DEMO:
var number = 42;
for (var number = 42; number <= 50; number++) {
if (number % 3 === 0) {
console.log(number);
}
}
The code will look like this
var number = 42;
for ( number = 42; number <=50; number++) {
if (number % 3===0) {
console.log(number); }
}
The number which returns 0 as the remainder when it is divisible by 3. So we check the remainder is equal to 0. if this condition satisfied console.log will print the number which is divisible by 3. if you need to push the numbers into new array, your code will look like this
var divBy3=[],number = 42;
for ( number = 42; number <=50; number++) {
if (number % 3===0) {
divBy3.push(number)
}
console.log(divBy3)
}
Related
could you please help me understand why the following line result is [1,3]?
[1,3,6].filter( item => item % 2)
I was expecting to receive the even number from the array.
Many thanks!
Filter checks for a boolean, 3 % 2 is equal to 1, which evaluates to true.
You want item % 2 == 0
Even numbers are those numbers that are exactly divisible by 2.
The remainder operator % gives the remainder when used with a number. For example,
const number = 6;
const result = number % 4; // 2
Hence, when % is used with 2, the number is even if the remainder is zero. Otherwise, the number is odd.
// program to check if the number is even or odd
// take input from the user
const number = prompt("Enter a number: ");
//check if the number is **even**
if(number % 2 == 0) {
console.log("The number is even.");
}
// if the number is **odd**
else {
console.log("The number is odd.");
}
ref : https://www.programiz.com/javascript/examples/even-odd
The number equals 100 ("this is not the code. I am illustrating the problem")
script : (
number: divider,
100/2 = 50 --> It can be divided by 2 again and still more than 0,
50/2 = 25 --> It can be divided by 2 again and still more than 0,
-->25/2 = It cannot be divided by 2 anymore(12.5)but it's still more than 0, so the divider goes up by one,
25/3 = but it's still more than 0, so the divider goes up by one,
25/4 = but it's still more than 0, so the divider goes up by one,
25/5 = 25/5 can be divided,
5 "===" 5 condition met
)
I currently stuck on --> step please help any other suggestion is greatly appreciated.
Reason: just trying to automate a math problem for my homework
Math problem: count how many times can the number be divided by 2, 3, 5...
var number = 100;
function howMuch(n, divider = 2){
if( Math.floor(n) !== n){
console.log(n)
if(n > 0){ //maybe here the condition is not right?
return howMuch( divider++)
} else return;
} else {
console.log(n)
return howMuch(n / divider)
}
}
console.log(howMuch(number))
There were a couple problems with the logic you had. Some are
divider was always 2
to see if something perfectly divides, like if n is perfectly divisible by a, n%a would be 0
There might be more but im not sure how to word it ;-;
//recursion example
function howMuch(n,divider){
divider=divider||2 //so that you can pass in divider values and default to 2 at the start
while(n%divider){divider++} //adds until divider can divide without remainder
console.log(`${n}/${divider}=${n/divider}`) //the log of the division statement
n/=divider //the division statement
if(n===divider){return "Success"} //when mission complete
return howMuch(n,divider) //else recurse
}
//example
//btw im not sure if u want it in 1 string or separate stings, but ur question code seemed like separate strings so that's what i did
console.log(howMuch(100))
You don't need recursion for this.
function howMuch(n) {
let divisor = 2;
while (true) {
let result = n / divisor;
if (result < 1) {
break;
}
if (result != Math.floor(result)) {
divisor++;
continue;
}
console.log(n, "/", divisor, "=", result);
n = result;
}
}
howMuch(100);
prints out
100 / 2 = 50
50 / 2 = 25
25 / 5 = 5
5 / 5 = 1
I'm having a hard time with this problem here:
Write a function named sumEvery5th that accepts a non-negative integer n and returns the sum of the integers divisible by 5 from 1 to n, including n itself. Use a for loop.
This is what I have so far:
var sumEvery5th = function(n){
let sum = 0;
for(let i = 1; n % 5 == 0; i++){
sum+ i
};
return sum;
}
I feel like I'm really close. Thanks for the help in advance.
You can start your loop at 5, since 1, 2... are not divisible by 5. And instead of i++, you can directly go 5 by 5, until i is greater than n:
var sumEvery5th = function(n) {
let sum = 0;
for (let i = 5; i <= n; i += 5) {
sum += i;
};
return sum;
}
console.log(sumEvery5th(10)); // 5 + 10 = 15
console.log(sumEvery5th(18)); // 5 + 10 + 15 = 30
First I think you should understand how a for loop works.
var sumEvery5th = function(n){
let sum = 0;
for(let i = 1; n % 5 == 0; i++){
sum+ i
};
return sum;
}
What you are doing, step by step, is:
Declaring a variable i with value 1.
Dividing n by 5 and taking the remainder value and comparing it with 0. In case it's true, you are skipping the code block inside the for and moving towards the return sum; line.
(In case you haven't skipped the code block in step 2) Run the code block with the new i value.
(In case you haven't skipped the code block in step 2) Incrementing the i value.
Go back to step 2.
Usually your for condition will depend in the variable declared in step 1. What you want to do is run the for code block n times.
For that, you need to change your condition from n % 5 == 0 to i <= n. This will make sure to run the code block while your i is less or equal than n, starting with a value of 1.
Now, inside your code block you add your divisible by 5 logic, checking against i value.
for(let i = 1; i <= n; i++){
if (i%5 == 0) sum += i;
};
Now let's say I called sumEvery5th(5).
Declare a variable i with value 1.
Check if i (1) is less than or equal n (5).
Go inside the code block.
Check if i%5 is 0.
It's not.
Increment i, now i = 2.
Check if i (2) is less than or equal n (5).
...And so on, until i = 6, and in that case the code block is skipped and the program will continue its course.
Ps.: There are ways to improve the performance of this algorithm, but now that you understand your for loop a bit better I'll leave it to you :)
var sumEvery5th = function(n){
let sum = 0;
for(let i = 1; i <= n; i++){
if (i % 5 === 0) {
sum += i;
}
}
return sum;
}
Hi can somebody tell me why the output to my function defaults to even when you insert over 17 numbers? It's probably super simple, please go easy on me!
function oddOrEven(number) {
var number = document.getElementById('number').value;
if(number % 2 != 0) {
document.getElementById('demo').innerHTML = "Odd";
}
else {
document.getElementById('demo').innerHTML = "Even";
}
if (number.length === 0) {
document.getElementById('demo').innerHTML = "Odd / Even";
}
}
You can simplify this whole thing. If you are always grabbing the input with id 'number' you don't need to pass a param, and then after a simple test you can inline the answer you want:
function oddOrEven(){
var val = document.getElementById('number').value;
var number = parseInt(val, 10);
// if it's not a valid number, you'll have NaN here which is falsy
if (number) {
document.getElementById('demo').innerHTML = (number % 2) ? "Even" : "Odd";
}
}
All that said, I just caught that you're talking about 17 digits (thanks to #JJJ's comment) rather than using the function more than once. The problem in this case is that JS integers have a size limit. If you parse anything larger it returns a number you're not going to expect. There are a lot of discussion of general handling of very large numbers here: http://2ality.com/2012/07/large-integers.html, but for your modulus problem you could take the last digit and check if that's odd or even like so:
function oddOrEven(){
var val = document.getElementById('number').value;
var number = parseInt(val, 10);
// if it's not a valid number, you'll have NaN here which is falsy
if (number) {
var lastDigit = val[val.length-1];
document.getElementById('demo').innerHTML = (parseInt(lastDigit, 10) % 2) ? "Even" : "Odd";
}
}
When trying out the code below as a solution for the Euler Project problem 5. The problem is find the smallest number equally divisible by all numbers from 1 to 20. Every time it is run it presents "Unresponsive Script" window and I need to physically stop the script from running. It seems like something is causing it to hang but I can't quite figure out what. The alert window seems to point to an error with the line the while() starts on but I can't see anything wrong with it.If it looks like it should work I'd appreciate anyone trying it on their machine to see if it works. That way I can eliminate it as a local problem. All suggestions welcome.
var divisible = false;
var n = 2520; // first number divisible by all numbers 1-10
while(divisible === false){ // something wrong here??
n += 2520;
for(var i = 11; i < n; i++) {
if(i % n !== 0){
break;
}
if(i === 20) {
divisible === true;
}
}
}
if(divisible === true){
return console.log("Answer: " +i);
}
Because you break out of your for loop if i % n isn't 0 the very first time. And you never set divisible to true - divisible === true isn't the same as divisible = true
There are several errors in the original code, some pointed out in the answer above. To make it work several fixes are needed.
First, the boolean divisible must be correctly set to true using the assignment operator = inside the for loop instead of === which is used only to check if two values are strictly of the same type AND value.
The next problem is the conditional part of the for loop i < n should be i < 20 because the loop is checking if numbers between 11 and 20 divide evenly into n.The last fix to make the code run correctly is the order of the condition if the first if statement which should read if(n % i !== 0) and not if(i % n !== 0). I think it might be this specific part that caused the code to crash and generate the "Unresponsive Script" alert in the browser.
Here is the fixed code.
var divisible = false;
var n = 2520; // smallest number divisible by all numbers 1-10
while(divisible === false){
n += 2520; // increment n on each new pass
// loop numbers between 11 and 20
for(var i = 11; i <= 20; i++) {
if(n % i !== 0){ // check if i divides equally into n
// if not break out of current loop and start again
break;
}
// if i reaches 20 then all the numbers divided equally into n
if(i === 20) {
// set value of divisible to true to cancel while loop
divisible = true;
}
}
}
// return the last value of n
return console.log("Answer: " +n);