I don't know how these 2 block of codes executes,they have different outputs, do I have to use else if on the first block, if so, which is faster?
demo
var output = 0;
for (var n = 0; n < 100; n++) {
if (n % 3 === 0) {
output += n;
}
if (n % 5 === 0) {
output += n;
}
}
console.log(output);
/* ------------------------- */
var sum = 0;
for (var x = 0; x < 100; x++) {
if (x % 3 === 0 || x % 5 === 0) {
sum += x;
}
}
console.log(sum);
If you use else if instead of the second if in the first block, you should get the same results.
For example, n=15:
in the first block of code:
you check n%3 === 0 is true, so output is increased by 15
you check n%5 === 0 is true, so output is increased by 15 again
in the second block of code:
you check n%3 === 0 is true, no other checks are done, sum is increased by 15
if you use else if:
you check n%3 === 0 is true, so output is increased by 15
no other checks are done
I believe || and else if speeds are pretty the same. Hope it helps
In the first block of code, for the numbers divisible by 15(lowest common multiple of 3 and 5), sum was getting added twice.
In the second block of code, as its a || statement. Only once sum was added if its a multiple of 15.
Check the third block of code, I added. I am just looking for the sum of the multiples of 15. See its the exact diff you were finding.
var output = 0;
for (var n = 0; n < 100; n++) {
if (n % 3 === 0) {
output += n;
}
if (n % 5 === 0) {
output += n;
}
}
console.log(output);
/* ------------------------- */
var sum = 0;
for (var x = 0; x < 100; x++) {
if (x % 3 === 0 || x % 5 === 0) {
sum += x;
}
}
console.log(sum);
/* ------------------------- */
sum = 0;
for (x = 0; x < 100; x++) {
if (x % 15 === 0) {
sum += x;
}
}
console.log(sum);
Related
I'm given a number and I need to find the sum of the multiples of 3 and 5 below the number.
For example:
20 => 78 = 3 + 5 + 6 + 9 + 10 + 12 + 15 + 18
My code works, but not for numbers greater than 1,000,000 (I tested it for 100,000 - it gives the result with 2sec delay). So, it should be optimized. Could someone help me? Why is my code slow? Thanks.
My logic is as follows:
add multiples to an array
filter duplicate values
sum all values
my code:
function sumOfMultiples(number) {
let numberBelow = number - 1;
let numberOfThrees = Math.floor(numberBelow / 3);
let numberOfFives = Math.floor(numberBelow / 5);
let multiples = [];
let multipleOfThree = 0;
let multipleOfFive = 0;
for (var i = 0; i < numberOfThrees; i++) {
multiples.push(multipleOfThree += 3);
}
for (var j = 0; j < numberOfFives; j++) {
multiples.push(multipleOfFive += 5);
}
return multiples
.filter((item, index) => multiples.indexOf(item) === index)
.reduce((a, b) => a + b);
}
You can also do this without using any loops.
For example if N is 1000, the sum of all multiples of 3 under 1000 is 3 + 6 + 9 ..... 999 => 3( 1 + 2 + 3 .... 333)
Similarly for 5, sum is 5(1 + 2 + 3 .... 200). But we have to subtract common multiples like 15, 30, 45 (multiples of 15)
And sum of first N natural numbers is N*(N+1)/2;
Putting all of this together
// Returns sum of first N natural numbers
const sumN = N => N*(N+1)/2;
// Returns number of multiples of a below N
const noOfMulitples = (N, a) => Math.floor((N-1)/a);
function sumOfMulitples(N) {
const n3 = noOfMulitples(N, 3); // Number of multiples of 3 under N
const n5 = noOfMulitples(N, 5); // Number of multiples of 5 under N
const n15 = noOfMulitples(N, 15); // Number of multiples of 3 & 5 under N
return 3*sumN(n3) + 5*sumN(n5) - 15*sumN(n15);
}
You can just run a loop from 1 to number, and use the modulo operator % to check if i divides 3 or 5:
function sumOfMultiples(number) {
var result = 0;
for (var i = 0; i < number; i++) {
if (i % 5 == 0 || i % 3 == 0) {
result += i;
}
}
return result;
}
console.log(sumOfMultiples(1000));
console.log(sumOfMultiples(100000));
console.log(sumOfMultiples(10000000));
You can do that just using a single loop.
function sumOfMultiples(number) {
let sum = 0;
for(let i = 1; i < number; i++){
if(i % 3 === 0 || i % 5 === 0){
sum += i;
}
}
return sum;
}
console.time('t');
console.log(sumOfMultiples(100000))
console.timeEnd('t')
You can do something like this
Set the difference equal to 5 - 3
Start loop with current as 0, keep looping until current is less than number,
Add 3 to current in every iteration,
Add difference to current and check if it is divisible by 5 only and less than number, than add it final result,
Add current to final result
function sumOfMultiples(number) {
let num = 0;
let difference = 5 - 3
let current = 0
while(current < number){
current += 3
let temp = current + difference
if((temp % 5 === 0) && (temp %3 !== 0) && temp < number ){
num += temp
}
difference += 2
if(current < number){
num += current
}
}
return num
}
console.log(sumOfMultiples(20))
console.log(sumOfMultiples(1000));
console.log(sumOfMultiples(100000));
console.log(sumOfMultiples(10000000));
you can do something like this
function multiplesOfFiveAndThree(){
let sum = 0;
for(let i = 1; i < 1000; i++) {
if (i % 3 === 0 || i % 5 === 0) sum += i;
}
return sum;
}
console.log(multiplesOfFiveAndThree());
I have few problems with JavaScript. I don't know why it's not working. I've searched the internet but didn't find anything.
I need to popup an alert if both number are equal to popup number (if they are equal) if not, an alert with message (Please insert numbers). But I can't make it work.
function even(){
var n = parseInt(document.getElementById("n").value);
var m = parseInt(document.getElementById("m").value);
var s = 0 ;
var i;
if (n < m) {
i = n;
while (i <= m){
if(i % 2 === 0)
s += i;
i++;
}
alert(s);
}
else if (n > m) {
i = m;
while (i <= n) {
if (i % 2 === 0)
s += i;
i++;
}
alert(s);
}
else if (n = m) {
i = m;
i = n;
while(i % 2 == 0)
s == i;
}
alert(s);
}
}
<input type="text" id="n" > </br><br>
<input type="text" id="m" > </br><br>
<button type="button" onclick="even()">Sum Even Numbers</button>
function even(){
var n = parseInt(document.getElementById("n").value);
var m = parseInt(document.getElementById("m").value);
if(n % 2 == 0 && m % 2 == 0){
alert(n + m);
}
}
This is way simpler and does work only if n & m are even numbers. Thanks to n % 2 == 0 and m % 2 == 0 which divide the numbers by to and check if the remainder is equal to 0.
EDIT
But reading your question again I'm not sure it is you want to achieve. You might want to be more precise.
Based on the code you have above, I assume goal is to sum the even numbers between n and m. Something like this? Perhaps,
function even() {
var n = parseInt(document.getElementById("n").value);
var m = parseInt(document.getElementById("m").value);
var s = 0;
var start = Math.min(n, m);
var end = Math.max(n, m);
for (var i = start; i <= end; ++i) {
if (i % 2 === 0) {
s += i;
}
}
alert(s);
}
jsFiddle
Notes
while(i%2 == 0) s == i; should probably be while(i % 2 == 0) { s = i; }
}else if(n=m) { should probably be } else if (n === m) {
I used Math.min() and Math.max() since it seemed like the first two sections of your if-statement did the same thing but with n and m swapped.
I looked for a function to determine if a number is prime and found this
for (var i = 2; i <= Math.sqrt(num); i++)
if (num % i === 0) {
return false;
}
return true;
and I don't understand why that works, yet this doesn't
for (var i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
return false;
}
return true;
}
What is it about the (lack of the) block statement that is functioning differently
Your first code looks like this:
for (var i = 2; i <= Math.sqrt(num); i++){
if (num % i === 0) {
return false;
}
}
return true;
Notice how return true is on the outside. Your second code doesn't work because it prematurely returns true when there are more numbers to check. Your entire for loop is equivalent to
return num % 2 !== 0;
which is clearly incorrect.
Let me tell you something about blocks that you might not have known (It took me a while to discover this at least).
When you use a loop or if-else statement, you can ignore the using braces { and }.
Example 1
if (a === b){
c = 0;
}
is actually the same as
if (a === b)
c = 0;
Example 2
for (i = 0; i < 10; i++){
a += 1;
}
is actually the same as
for (i = 0; i < 10; i++)
a += 1;
However 1
if (a === b){
c = 0;
d = 1;
}
is not the same with
if (a === b)
c = 0;
d = 1;
However 2
for (i = 0; i < 10; i++){
a += 1;
b += 1;
}
is not the same with
for (i = 0; i < 10; i++)
a += 1;
b += 1;
Explanation
In loops and if-else statement, the block statement (codes surrounded by { and } groups the codes within it and execute it.
However, in the absence of { and }, the loops or if-else statement will only execute the single line of code after it.
Meaning,
var a = 0,
b = 0;
for (i = 0; i < 10; i++)
a += 1;
b += 1;
In this case, a === 10 but b === 1.
Also, in the following case,
var a = 0,
b = 0;
if (false)
a = 10;
b = 10;
a === 0 but b === 10.
var number = prompt('Input a number!');
var n = number;
function getList() {
for (var n = 1; n <= 17; n++) {
if (n % 3 == 0 || n % 5 == 0)
console.log (n);
}
}
console.log(getList());
console.log((n*(n+1))/2);
//equation for summation: (n*(n+1))/2
I'm trying to return the sum of numbers divisible by 3 or 5 up to 17. So far, it half-works; it lists all the numbers, but I can't find a way to return the sum.
I have the equation for summation, but I can't find a way to put it in so that it works. How do you get the equation to reference the list instead of referencing the inputted number?
The answer is supposed to be 60. Any clue? Thanks!
var sum = 0;
for (var n = 1; n <= 17; n++) {
if (n % 3 === 0 || n % 5 === 0)
sum += n;
}
console.log(sum);
Use a variable to add the numbers and return it after for loop.
Below it the exapmle.
function getList() {
var sum = 0;
for (var n = 1; n <= 17; n++) {
if (n % 3 == 0 || n % 5 == 0) {
sum += n;
}
}
return sum;
}
console.log(getList());
Two things:
Just return the sum from your getList function
Make sure your prompt input is converted to integer otherwise it will be treated as a string and your n*(n+1)/2 will be wrong
var number = parseInt(prompt('Input a number!'));
var n = number;
function getList() {
var sum = 0;
for (var n = 1; n <= 17; n++) {
if (n % 3 == 0 || n % 5 == 0) {
console.log (n);
sum += n;
}
}
return sum;
}
console.log(getList());
console.log(n, (n*(n+1))/2);
If you want an equation :)
function sumOfNumbersDivisibleBy3Or5(n) {
const by3 = Math.floor(n/3),
by5 = Math.floor(n/5),
by3And5 = Math.floor(n/3/5);
return 3*by3*(by3+1)/2 + 5*by5*(by5 + 1)/2 - 3*5*by3And5*(by3And5 + 1)/2
}
console.log(sumOfNumbersDivisibleBy3Or5(17))
var number = prompt('Input a number!');
function getList() {
var sum = 0;
for (var n = 1; n <= number; n++) {
if (n % 3 == 0 || n % 5 == 0)
sum+=n;
}
return sum;
}
console.log(getList());
it will return sum of all the number which is divisible by 3 or 5 in between 1 and entered number
I'm kinda new to programming and I got this question in a quiz. I need to write a JavaScript program to read 10 positive values from the user, and then sum only the multiples of 3 and 5.
I couldn't even finish the code. help?
var x = new Array ();
var total;
x.push(parseFloat(window.prompt("enter a value",""),));
for (x.length<=10; i=0; i<10; i++) {
total += x[i]
}
else{
document.write(total);
}
You need to put your prompt function inside for loop and add check if number is multiply by 3 or 5.
var total;
for (var i=0; i<10; i++) {
var num = parseFloat(window.prompt("enter a value",""));
if (num % 3 == 0 || num % 5 == 0) {
total += num;
}
}
document.write(total);
UPDATE:
var total;
var i = 0;
while (i<10) {
var num = parseFloat(window.prompt("enter a value",""));
if (num >= 0 && (num % 3 == 0 || num % 5 == 0)) {
total += num;
i++;
}
}
document.write(total);
thanks, i did set total=0 so that after the sum it prints out a value instead of NaN
var total = 0;
var i = 0;
while (i < 10) {
var num = parseFloat(window.prompt("enter a value", ""));
if (num >= 0 && (num % 3 == 0 || num % 5 == 0)) {
total += num;
i++;
}
}
document.write(total);