javascript - functions and equations confusion - javascript

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

Related

Sum All Primes Below a Given Number | Intermediate Javascript Algorithm | Recursion

Question
A prime number is a whole number greater than 1 with exactly two divisors: 1 and itself. For example, 2 is a prime number because it is only divisible by 1 and 2. In contrast, 4 is not prime since it is divisible by 1, 2 and 4.
Rewrite sumPrimes so it returns the sum of all prime numbers that are less than or equal to num.
My Attempt
const isPrime = a => {
for(let i = 2; i < a; i++)
if(num % i === 0) return false;
return a > 1;
}
function sumPrimes(num, total = []) {
let numVar = num;
let n = total.reduce((aggregate, item)=>{
return aggregate + item;
}, 0);
if(n > numVar){
return n;
}
for(let i = 1; i <= numVar; i++){
if(isPrime(i)== true){
total.push(i);
}
}
return sumPrimes(num, total);
}
sumPrimes(10);
The Problem
It says: 'Num is not defined'
I am not sure if there are other errors.
My Question
Please could you help me find the error, and fix the code to solve the algorithm?
This was a simple syntax error identified by #Jonas Wilms (upvote him in the comment above :))!
By replacing the 'a' with 'num' the function was fixed.
const isPrime = a => {
for(let i = 2; i < a; i++)
if(a % i === 0) return false;
return a > 1;
}
function sumPrimes(num, total = []) {
let numVar = num;
let n = total.reduce((aggregate, item)=>{
return aggregate + item;
}, 0);
if(n > numVar){
return n;
}
for(let i = 1; i <= numVar; i++){
if(isPrime(i)== true){
total.push(i);
}
}
return sumPrimes(num, total);
}
console.log(sumPrimes(10));
this simple function may help you,
function isPrime(num) {
for (var i = 2; i < num; i++)
if (num % i === 0) return false;
return num > 1;
}
function sumPrimes(num) {
let tot = 0;
for (let i = 0; i < num; i++)
if (isPrime(i))
tot += i;
return tot;
}
console.log(sumPrimes(10));

find sum of multiples 3 and 5, JS

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());

Find and print the biggest prime number (JS)

I'm studying node.js and have some interesting task - Write a program that finds and prints the biggest prime number which is <= N.
Input // Output - 13 // 13
126 // 113
26 // 23
In last course with java i have the same task and my code is really simple:
import java.util.Scanner;
public class BiggestPrimeNumber {
public static void main(String[] args){
int n;
Scanner in = new Scanner(System.in);
n=in.nextInt();
while(prim(n) == false){
n--;
}
System.out.println(n);
}
public static boolean prim(int m){
int n=m;
for(int i=2;i<n;i++){
if(n%i == 0){
return false;
}
}
return true;
}
}
I try similar way to test it, but I'm don't have idea how to convert it:
let n = 126;
while (isPrime(n) === false) {
n -= 1;
}
console.log(n);
let n = m;
for (let i = 2; i < n; i += 1) {
if (n % i === 0) {
return false;
}
}
return true;
Can you help me, because I'm really have problem with js using in console.
I think this is what you want. You only need to declare a function and use it as you are doing.
let n = 126;
while (isPrime(n) === false) {
n -= 1;
}
console.log(n);
function isPrime(m) {
let n = m;
for (let i = 2; i < n; i += 1) {
if (n % i === 0) {
return false;
}
}
return true;
}
If your running it with NodeJS in console, you can save it in a file called prime.js (for example) and execute it with: node prime.js.
You can pass parameters to the script like: node prime.js 126 and then get them in the code. That will be something like that:
const args = process.argv;
let n = args[2];
while (isPrime(n) === false) {
n -= 1;
}
console.log(n);
function isPrime(m) {
let n = m;
for (let i = 2; i < n; i += 1) {
if (n % i === 0) {
return false;
}
}
return true;
}
You're pretty close. First off, you don't have isPrime defined. Second, if you were to paste all of your code into the browser console, it isn't going to like that you are defining n twice. I also cleaned up your isPrime bit of code.
let n = 100;
let result = n;
const isPrime = num => {
for(let i = 2; i < num; i++)
if(num % i === 0) return false;
return num !== 1 && num !== 0;
}
while (isPrime(result) === false) {
result -= 1;
}
console.log(result + " is the next prime below " + n);
Also, remember that javascript is not a compiled language, so unless you are defining your function in a class, the browser will interpret the code sequentially. Therefore, you have to have isPrime defined before you use it.
The algorithm to find the nearest prime number can be further optimized. All prime numbers are of the form 6k+1 or 6k-1 except the numbers 2 and 3. Also, instead of checking all the way to the number the check can be made till Sqrt(n). Here is the modified isPrime function:
let n = 126;
while (isPrime(n) === false) {
n -= 1;
}
console.log(n);
function isPrime(num) {
if (num <= 1) return false;
if (num < 4) return true;
if (num%2 === 0 || num%3 === 0) return false;
for (var i = 5; i*i <= num; i+=6) {
if (num % i === 0 || num % (i + 2) === 0)
return false;
}
return true;
}

How does (else) if and || work and which is better?

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);

for/while loop for reading user input

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);

Categories

Resources