Finding multiples of 7 between 2 given integers - javascript

I'm trying to return a string (a comma-separated list) of all numbers between two given integers that are multiples of 7. I know how to find the multiples with the modulus operator but not between 2 given numbers. I'm new to JS and learning. Help is greatly appreciated.
Starting with something like this:
function findMultiplesOfSeven(startNumber, endNumber) {
return string;
}

You could take the start value and add the remainder value for getting the first wanted value.
i = startValue + startValue % 7 // 5 + 2 => 7
Then iterate and loop until the value is greater then the end value.
for (i = startValue + startValue % 7; i <= endValue; i += 7) {
// add value
}

Here is my sample code:
function findMultiplesOfSeven(startNumber, endNumber) {
let multiples = [];
let walk = startNumber + (7 - startNumber % 7);
while(walk <= endNumber) {
multiples.push(walk);
walk += 7;
}
let string = multiples.join(',')
return string;
}

function findMultiplesOfSeven(startNumber, endNumber) {
let containsNumberDivisibleBy7 = false;
let firstNumber;
let numbers = [];
for (var i = startNumber; i <= endNumber; i++) {
if (i % 7 === 0) {
containsNumberDivisibleBy7 = true;
firstNumber = i;
break;
}
}
if (containsNumberDivisibleBy7) {
for (var i = firstNumber; i <= endNumber; i += 7) {
numbers.push(i);
}
}
return numbers.join(",");
}

Related

Cheking if it's a prime number with JS

I'm first trying to push only prime numbers (without 2) to an array and then sum them all but getting undefined.
I've been working on this for long days, I'd appreciate if anyone could help me.
let letsCheck = () => {
let ourList = []
let sum = 0
for(let i = 2; i <= 50; i++) {
if(i % 2 !== Number.isInteger()) {
ourList.push(Number(i))
}
}
for(let prime in ourList) {
sum += ourList[prime]
}
}
First of all, You are not checking prime but checking odd numbers by % operator.
Second, you are checking Number.isNumber function which will return the boolean so, the comparison have some issues.
Here is one solution which may help.
let letsCheck = () => {
let ourList = []
let sum = 0
for(let i = 3; i <= 50; i++) {
if(isPrimeNumber(i)) {
ourList.push(Number(i))
}
}
for(let prime in ourList) {
sum += ourList[prime]
}
}
const isPrimeNumber = number => {
for(let i = 2; i <= Math.ceil(number/2); i++) {
if(number % 2 === 0) {
return false;
}
}
return true;
}
From, your code, it was more likely for obtaining odd/even numbers instead of prime numbers.
Prime numbers are whole numbers greater than 1, that have only two factors – 1 and the number itself
Odd numbers are the numbers that doesn't have 2 as its factor, and will have remainder = 1 if it gets divided by 2.
Then, as the basic programming math, the mod works like multiplication/add/subtraction that if both operators/numbers are Integer, the result would be Integer. The mod operation is basically for obtaining the remainders from the division, i.e. 5 / 2 = 2, with remainders = 1, thus 5 % 2 = 1.
And, in the looping, the i is already a number, so pushing the Number(i) is equivalent with pushing i alone. If you just want to get the sum, the array is not necessary there and should be just removed. You can get the sum by accumulate it into the sum variable.
Thus, if you wish to get the sum of odd numbers in the range [2,50], it should be:
let letsCheck = () => {
let sum = 0
for(let i = 2; i <= 50; i++) {
if(i % 2 !== 0) {
sum += i;
}
}
console.log(sum);
}
letsCheck();
And if you wish to get the prime numbers from 0 to 50 excluding 2, it should be:
function isPrimeExclude2(num) {
if(num <= 2) return false;
for(let i=2; i*i <= num; i++){
if (num % i == 0) return false;
}
return true;
}
let letsCheck = () => {
let sum = 0
for(let i = 2; i <= 50; i++) {
if(isPrimeExclude2(i)) {
sum = sum + i;
}
}
console.log(sum);
}
letsCheck();

How Can I find the first number greater than const M?

I have a problem with this. I have to find the first prime number greater than my const M.
For example, I have M = 11, and I have to find the first prime number greater than M and it is 13.
How Can I do that?
// isPrime
const M = 11
function isPrime(num) {
if (num < 2) return false;
for (let i = 2; i < num; i++) {
if (num % i == 0) return false;
}
return true;
}
console.log(isPrime(M))
And I would like find for M = 11, primeNumber = 13, for M = 15, primeNumber = 17 etc.
You can iterate from M+1 until you find your prime number. You can do the following,
function isPrime(num) {
if (num < 2) return false;
for (let i = 2; i < num; i++) {
if (num % i == 0) return false;
}
return true;
}
findGreaterPrime = (m) => {
let i = m+1;
let found = false;
while(!found) {
if(isPrime(i)) {
found = true;
return i;
}
i++;
}
}
console.log(findGreaterPrime(11));
console.log(findGreaterPrime(13));
By the way, this method will be very slow for larger numbers. You can use some fast prime generators. You can follow the answers in this thread.
Simple and fast solution, via prime-lib (I'm the author).
The example below generates 2 primes, starting with 7 and upward:
import {generatePrimes, stopOnCount} from 'prime-lib';
const i = generatePrimes({start: 7}); // infinite prime-iterator
const s = stopOnCount(i, 2); // stop-iterator
const values = [...s]; // 7, 11
It checks if start is a prime, to be included then. If you need only a prime that follows, just check if the first number matches your M number, then take the next one instead:
if(values[0] === M) {
// use values[1]
} else {
// use values[0]
}

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

Check Digit Sum Javascript- recursion [duplicate]

This question already has answers here:
Adding digits from a number, using recursivity - javascript
(6 answers)
Closed 8 months ago.
Looking for Javascript solution in recursion to get the sum of all digits in number until single digit come as result
For example, for the number is "55555" the sum of all digits is 25. Because this is not a single-digit number, 2 and 5 would be added, and the result, 7.
I tried the below solution based on the algorithm.
function getSum(n) {
let sum = 0;
while(n > 0 || sum > 9)
{
if(n == 0)
{
n = sum;
sum = 0;
}
sum += n % 10;
n /= 10;
}
return sum;
}
console.log(getSum("55555"));
This would kind of work, but I'm almost sure there's a beautiful one-line solution which I just don't see yet.
function singleDigitSum(str) {
str = [...str].reduce((acc, c) => { return Number(c) + acc }, 0)
while (str.toString().length > 1) {
str = singleDigitSum(str.toString());
}
return str
}
console.log(singleDigitSum("55555"))
Explanation:
As a first step in your function you reassign to the parameter passed to the function the result of a reducer function which sums up all numbers in your String. To be able to use Array.prototype.reduce() function, I'm spreading your str into an array using [...str].
Then, for as often as that reducer returns a value with more than one digit, rinse and repeat. When the while loop exits, the result is single digit and can be returned.
function checSumOfDigit(num, sum = "0") {
if (num.length == 1 && sum.length !== 1) {
return checSumOfDigit(Number(sum) + Number(num) + "", "0");
} else if (num.length == 1) {
return Number(sum) + Number(num);
}
num = num.split("")
sum = Number(sum) + Number(num.pop());
return checSumOfDigit(num.join(""), sum + "")
}
console.log(checSumOfDigit("567"));
console.log(checSumOfDigit("123"));
console.log(checSumOfDigit("55555"));
this code might be help you
If you need a recursion try this one
function CheckDigitSum(number) {
let nums = number.split('');
if (nums.length > 1) {
let sum = 0;
for (let i = 0; i < nums.length; i++) {
sum += Number(nums[i]);
}
return CheckDigitSum(sum.toString());
} else {
return parseInt(nums[0], 10);
}
}
Here you go:
function createCheckDigit(num) {
var output = Array.from(num.toString());
var sum = 0;
if (Array.isArray(output) && output.length) {
for ( i=0; i < output.length; i++){
sum = sum + parseInt(output[i]);
}
if ((sum/10) >= 1){
sum = createCheckDigit(sum);
}
}
return sum;
}
This can be calculated by recursive function.
function createCheckDigit(membershipId) {
// Write the code that goes here.
if(membershipId.length > 1){
var dgts = membershipId.split('');
var sum = 0;
dgts.forEach((dgt)=>{
sum += Number(dgt);
});
//console.log('Loop 1');
return createCheckDigit(sum + '');
}
else{
//console.log('Out of Loop 1');
return Number(membershipId);
}
}
console.log(createCheckDigit("5555555555"));
function checkid(num) {
let sum = 0;
let s = String(num);
for (i = 0; i < s.length; i++) {
sum = sum + Number(s[i]);
}
if(String(sum).length >= 2) return checkid(sum)
else return sum;
}
console.log(checkid(55555);

function sumDigits; How do I get this function to work with a negative number?

Question:
Write a function called sumDigits.
Given a number, sumDigits returns the sum of all its digits.
var output = sumDigits(1148);
console.log(output); // --> 14
If the number is negative, the first digit should count as negative.
var output = sumDigits(-316);
console.log(output); // --> 4
This is what I currently have coded and it works for positive values but I can't wrap my head around how to tackle the problem when given a negative value. When -316 is put into the function, NaN is returned and I understand that when I toString().split('') the number, this is what is returned: ['-', '3', '1', '6']. How do I deal with combining index 0 and 1?
function sumDigits(num) {
var total = 0;
var newString = num.toString().split('');
for (var i = 0; i < newString.length; i ++) {
var converted = parseInt(newString[i]);
total += converted;
}
return total;
}
sumDigits(1148);
Any hints on what methods I should be using? and is there a smarter way to even look at this?
This should do it:
function sumDigits(num) {
var total = 0;
var newString = num.toString().split('');
for (var i = 0; i < newString.length; i ++) {
if(newString[i]==='-') { //check to see if the first char is -
i++; //if it is, lets move to the negative number
var converted = parseInt(newString[i]); // parse negative number
total -= converted; // subtract value from total
continue; // move to the next item in the loop
}
var converted = parseInt(newString[i]);
total += converted;
}
return total;
}
console.log(sumDigits(-316));
You could always use String#replace with a function as a parameter:
function sumDigits (n) {
var total = 0
n.toFixed().replace(/-?\d/g, function (d) {
total += +d
})
return total
}
console.log(sumDigits(-1148)) //=> 14
One way to do this, is to do a split that will keep the minus and the first digit together, not split.
You can do that with a regular expression, and use match instead of split:
var newString = num.toString().match(/-?\d/g);
function sumDigits(num) {
var total = 0;
var newString = num.toString().match(/-?\d/g);
for (var i = 0; i < newString.length; i++) {
var converted = parseInt(newString[i]);
total += converted;
}
return total;
}
var result = sumDigits(-316);
console.log(result);
In a bit shorter version, you could use map and reduce, like this:
function sumDigits(num) {
return String(num).match(/-?\d/g).map(Number).reduce( (a, b) => a+b );
}
console.log(sumDigits(-316));
Is there a smarter way to even look at this?
You can avoid the conversion from number to string and back by using the modulo operator to extract the last digit. Repeat this step until you got all digits:
function sumDigits(num) {
let total = 0, digit = 0;
while (num != 0) {
total += digit = num % 10;
num = (num - digit) * 0.1;
}
return total < 0 ? digit + digit - total : total;
}
console.log(sumDigits(-316)); // 4
console.log(sumDigits(1148)); // 14
console.log(sumDigits(Number.MAX_SAFE_INTEGER)); // 76
function sumDigits(num) {
let string = num.toString();
let zero = 0;
let total = 0;
for (var i = 0; i < string.length; i++) {
if (Math.sign(num) === 1) {
total = zero += Number(string[i]);
} else {
for (var i = 2; i < string.length; i++) {
total = (zero += Number(string[i])) - Number(string[1]);
}
}
}
return total;
}

Categories

Resources