It's a function that returns the sum of all of the odd Fibonacci numbers that are less than or equal to the given number.
I am stuck with the last of the tests, all of them work besides this one.
sumFibs(75025) should return 135721, I've been trying many things but none worked.
function sumFibs(num) {
let f1 = 1;
let f2 = 1;
let fiboNums = [];
while (f1 <= num && f2 <= num) {
if (f1 % 2 !== 0) fiboNums.push(f1);
if (f2 % 2 !== 0) fiboNums.push(f2);
f1 += f2;
f2 += f1;
}
return fiboNums.reduce((pV, cV) => pV + cV);
}
console.log(sumFibs(75025));
Instructions: Given a positive integer num, return the sum of all odd Fibonacci numbers that are less than or equal to num.
The first two numbers in the Fibonacci sequence are 1 and 1. Every additional number in the sequence is the sum of the two previous numbers. The first six numbers of the Fibonacci sequence are 1, 1, 2, 3, 5 and 8.
For example, sumFibs(10) should return 10 because all odd Fibonacci numbers less than or equal to 10 are 1, 1, 3, and 5.
I tried changing the boolean statement of the while loop as well as the if-statements by adding a condition that evaluates to true if f1 or f2 are less than or equal to the given number
The issue is that once f2 is bigger than num, the loop ends even though f1 is not bigger than num, therefore skipping the last relevant number in the series and excluding it from the results. Here's a revised version that fixes the problem:
function sumFibs(num) {
let f1 = 1;
let f2 = 1;
let fiboNums = [];
while (f1 <= num) {
if (f1 % 2 !== 0) fiboNums.push(f1);
if (f2 <= num && f2 % 2 !== 0) fiboNums.push(f2);
f1 += f2;
f2 += f1;
}
return fiboNums.reduce((pV, cV) => pV + cV);
}
console.log(sumFibs(75025));
Related
Currently trying to complete the persistent bugger kata in code wars.
I need to return the number of times the input has to be multiplied until it is reduced to a single number (full task instructions below).
Everything appears to work apart from the count. when I console log, the number of times it logs and runs is correct, but instead of incrementing such as 1,2,3 it will be something like 2,2,4.
So instead of returning 3, it returns 4.
I try to not ask for help with katas, but this time I am completely at a loss as to why the count is firstly skipping numbers and also not incrementing.
Task:
Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.
For example:
persistence(39) === 3 // because 3*9 = 27, 2*7 = 14, 1*4=4
// and 4 has only one digit
persistence(999) === 4 // because 9*9*9 = 729, 7*2*9 = 126,
// 1*2*6 = 12, and finally 1*2 = 2
persistence(4) === 0 // because 4 is already a one-digit number
My function:
function persistence(num) {
//console.log('here', num)
if(num < 10) return 0;
if(num === 25) return 2
let spl = num.toString().split('');
let result = 1;
let count = 1;
spl.forEach((s) => {
let int = parseInt(s)
result *= int;
//count++;
})
//console.log(result)
if(result > 9) {
persistence(result)
count++;
}
// console.log('count-->', count)
return count;
}
A sub issue is that the input 25 always returns a count 1 less than it should. My fix is poor I know, again any advice would be much appreciated.
Spoiler alert: this contains a solution. If you don't want that, stop before the end.
You don't really want to work with count, since as people point out, it's a local variable. You also don't work too hard to special case the result if it's a single digit. Let the recursion handle it.
Thus:
function persistence(num) {
//console.log('here', num)
if(num < 10) return 0;
//still here, must be 2 or more digits
let spl = num.toString().split('');
let result = 1;
spl.forEach((s) => {
let int = parseInt(s)
result *= int;
})
//console.log(result)
return 1 + persistence(result)
}
As you already have a complete solution posted here with fixes to your implementation, I will offer what I think is a simpler version. If we had a function to create the digit product for us, then persistence could be this simple recursion:
const persistence = (n) =>
n < 10 ? 0 : 1 + persistence (digProduct (n))
You already have code for the digit product, and while it's fine, a mathematical approach, rather than a string-base one, is somewhat cleaner. We could write it -- also recursively -- like
const digProduct = (n) =>
n < 10 ? n : (n % 10) * digProduct (Math .floor (n / 10))
or instead we might choose (n / 10) | 0 in place of the floor call. Either is reasonable.
Putting it together, we have:
const digProduct = (n) =>
n < 10 ? n : (n % 10) * digProduct ((n / 10) | 0)
const persistence = (n) =>
n < 10 ? 0 : 1 + persistence (digProduct (n))
const tests = [39, 999, 4, 25]
tests.forEach (n => console.log (`${n} --> ${persistence(n)}`))
I have this problem for my CIS class: "Write a function named sumOfProperDivisors that accepts an integer n > 1, and returns the sum of the proper divisors of n.(A proper divisor is a positive divisor of a number, excluding the number itself. For example, 1, 2, and 3 are proper divisors of 6, but 6 itself is not.) Use a for loop, and use function expression syntax."
I don't even know where to start. This is all I have so far and I'm pretty sure it's completely wrong. PLEASE I NEED HELP
var sumOfProperDivisors = function(n > 1) {
let sum = 0;
for (var i = 1; i <= n; i++)
// we don't have to search all numbers from 2 to the integer part of n / 2,
// but from 2 to the integer part of the square root of n
// if n = 1000 we look for divisors in the interval [2, 31] and not in [2, 500]
const sumOfProperDivisors = n => {
const root = Math.sqrt(n);
let result = 1 + Number.isInteger(root) * root;
for (let k = 2; k < root; k++) {
if (n % k === 0) result += k + n / k;
}
return result;
}
console.log(sumOfProperDivisors(6));
console.log(sumOfProperDivisors(1000));
console.log(sumOfProperDivisors(1000000));
Welcome to Stack Overflow
Read about asking homework questions - How do I ask and answer homework questions?
Also, read about asking a good question - https://stackoverflow.com/help/how-to-ask
The answer:
You can do it like this:
loop over from i = 1 to i = n/2 because once it cannot be divisible by something greater and n/2 and n.
if the modulo (remainder) of n / i is zero then increment sum
return sum
function sumOfProperDivisors(n) {
let sum = 0;
for (var i = 1; i <= n/2; i++){
if (n % i == 0){
sum++;
}
}
return sum;
}
console.log(sumOfProperDivisors(6))
The laziest way to do this is loop through all the numbers before n, 1 to n-1
and check if the modulo of n with the number gives 0 that means n is divisible by that number then add that number to a variable "sum" each time the condition applies.
You can alter some details like looping from 1 to n/2 to remove unnecessary numbers.
When you define a function, what goes in the parenthesis is the name of the argument, possibly with a default argument value, but the > 1 syntax you're using is not valid.
So, instead of:
function (n>1) {...}
You would need to do something like:
function (n) {
if (n <= 1) {
// ... throw an error or something...
// or maybe you don't need to bother with this?
// it's not super clear to me from the assignment
}
The other thing I would point you to in order to answer your question is the modulo operator, which is the percent sign (%) in javascript. That operator will return the remainder of a division operator, so if you want to check if a number is divisible by another number, you can check if the remainder is 0 in this way...
if (3 % 2 === 0) { console.log('3 is divisible by 2')}
if (4 % 2 === 0) { console.log('4 is divisible by 2')}
if (5 % 2 === 0) { console.log('5 is divisible by 2')}
One final note: it's nice to write a bunch of tests for yourself to see how your function works and see if you understand it. So if I got this problem as homework, the first thing I might do is write a bunch of statements to test out my answer and see how they work...
For example:
console.log('sumOfProperDivisors(4) should be 3... and it is ',sumOfProperDivisors(4))
console.log('sumOfProperDivisors(5) should be 1... and it is ',sumOfProperDivisors(5))
console.log('sumOfProperDivisors(6) should be 6... and it is ',sumOfProperDivisors(6))
console.log('sumOfProperDivisors(8) should be 7... and it is ',sumOfProperDivisors(8))
function findProperDivisor(num) {
if(num<0) return
let sum = 0;
for (let i = 0; i < Math.floor(num / 2); i++) {
if (num % i === 0) {
sum += i;
}
}
return sum
}
I'm currently trying to display number series (for 2, 3, 4, 5, 6 and 7) in JavaScript. I was looking for the smallest number (x), which results in modulo = 1, if divided by 2, 3, 4, 5 and 6. If the same number (x) is divided by 7, id should result in modulo = 0. I'm not quite sure, if I'm explaining it correct. It should be like this: x % 2 = 1, x % 3 = 1, x % 4 = 1, x % 5 = 1, x % 6 = 1, x % 7 = 0.
The result is 301. My code looks like this and it works fine:
var seven = 7;
var six;
var five;
var four;
var three;
var two;
while (six != 1 || five != 1|| four != 1|| three != 1|| two != 1)
{six = seven % 6;
five = seven % 5;
four = seven % 4;
three = seven % 3;
two = seven % 2;
console.log(seven);
seven += 7;}
It displays all the numbers in the seven-series, until 301. Now, I wanted some more while-loops for the other numbers (2-6), that work the same why and show all the different numbers/steps in each series, until 301. I'm new to JavaScript and I just don't get it. I tried to modify my code, so that it should work with the other number series, but it doesn't. Or is there any other (maybe a better) way to do this? With some nested loops/functions? It only should be possible to display every number in each number series, but not all at the same time (in the end, there should be buttons, which show (by clicking them) the different number series with all the numbers/steps until 301). Thank you soso much!
When doing this you should probably use a loop to simplify your life.
Start x at 0 and iterate to (for example) 100.000.
For every iteration, check to see if x % 2 / 3 / 4 / 5 / 6 is equal to 0. Then check to see if x % 7 === 1. If both these conditions are true, log the value and break the for loop.
The smallest value that answers this seems to be 120.
const numbers = [2,3,4,5,6]
const special = 7;
for(let x = 0; x < 100000; x++){
const isModulo0ForAllNumbers = numbers.every(n => (x % n) === 0);
const isModulo1ForSpecial = (x % special) === 1;
if(isModulo0ForAllNumbers && isModulo1ForSpecial){
console.log(`Smallest number found: ${x}`);
break;
}
}
Sometimes this is not possible to find such a number and you'll get infinite loop with unexpected behavior. This is a possible approach (see the comments inside):
// first define the greatest common divisor
// for two numbers - we'll need that later
let gcd = function(a, b) {
// classic 'Euclidean' method with recursion
if(a == 0) {
return b;
}
if(a > b) {
return gcd(b, a);
}
return gcd(b % a, a);
}
// define your series
let series = [2,3,4,5,6,7];
// now you need least common multiple for all numbers
// except for the last one
lcm = series[0];
for (let i = 1; i < series.length - 1; i++) {
lcm *= series[i] / gcd(lcm, series[i])
}
// the last number from series
let last = series[series.length - 1];
// exercise: you can research or think for smarter solution
// I will just loop until we get the result
if(gcd(lcm, last) == 1) {
let r = lcm + 1;
while(r % last) {
r += lcm;
}
console.log('number found: ', r);
} else {
// not possible
console.log('impossible to find the number');
}
You could take an array of values for the modulo calculation and use a function for getting a check of a value.
const f = x => [2, 3, 4, 5, 6].every(v => x % v === 1) && x % 7 === 0;
var value = 0;
while (!f(value)) value += 7;
console.log(value);
I am fairly new to programming, just knowing the basics in Javascript and Swift. I am trying to write a simple program which creates, from any entered number, a two digit number by summing up the first and last digit until only two digits are finally left.
Here is an example:
num = 1234567:
1+7 = 8
2+6 = 8
3+5 = 8
4 remains
So the first result is: 8884. Now everything is added again:
8+8 = 16
8+4 = 12
The result is 1612. Again everything is summed up:
1+2 = 3
6+1 = 7
The result is 37 - which is also the final result.
I am struggling with two things. First the while loop. I was thinking about casting num.toString() and then do a while loop like this in which I change the string to an int again:
num.toString()
while (num.length > 2) {
num = num.parseInt(num, 10);
...
}
But this doesn't work properly, plus it gets crazy complicated I guess because I would have to switch between string and int each new round, right?
I know how to add all digits together until I get a two digit number (it took me a while to figure this one out) and I am not even sure if this is a good way to do it:
var sum = num
.toString()
.split('')
.map(Number)
.reduce(function (a, b) {
return a + b;
}, 0);
But obviously I cannot use this here and I have no idea how to change the code so that the first and last digit are added together.
Slightly different approach:
function sum(num) {
var numString = num.toString();
var newString = "";
while (numString.length > 1) { // (1)
newString += (parseInt(numString[0]) + parseInt(numString[numString.length - 1])).toString(); // (2)
numString = numString.substring(1, numString.length - 1); // (3)
}
newString += numString; // (4)
if (newString.length > 2) { // (5)
console.log(newString)
return sum(newString);
} else {
return newString;
}
}
console.log(sum(1234567));
Outputs:
8884
1216
73
Brief explanation of what's going on:
(1) Your while loop will process the string until there's either 1 or
0 characters left
(2) Add the sum of your first and last character to
your newString
(3) Remove the first and last characters from your
numString now that they've been saved to the newString. Because
you're overwriting the value in numString and shrinking it, this
will eventually satisfy the while condition of a numString with
less than 2 characters
(4) Add the remaining characters to
newString, which will either be 1 or 0 characters depending on the
length of the original number
(5) if your newString is more than 2
characters, run this method again. Otherwise return your result
Try this buddy. Its just using simple for loop. Its loops upto half of number and add corresponding. The final result according to ur logic should be 73 not 37
function sum(num){
//if num is greater than or equal to 2 end the function and return final value
if(num.length <= 2) return num;
//converting the num to string beacuse first time input will be number
num = String(num);
let result = '';
//creating a loop upto half of length of the num
for(let i = 0;i<num.length/2;i++){
//if the number is not middle one
if(i !== num.length - 1 - i)
{
//adding the sum of corresponding numbers to result
result += parseInt(num[i]) + parseInt(num[num.length - 1 - i]);
}
//if the number is middle number just add it to result
else result += num[i]
}
return sum(result);
}
console.log(sum(1234567))
You could take a nested while loop and check the string length for the outer loop and the left and right indices for the inner loop
function add(n) {
var s = n.toString(),
l, r,
sum;
while (s.length > 2) {
l = 0;
r = s.length - 1;
sum = [];
while (l < r) {
sum.push(+s[l++] + +s[r--]);
}
if (l === r) sum.push(s[l]);
s = sum.join('');
}
return +s;
}
console.log(add(1234567));
The same but with a recursive function.
function add(n) {
var s = n.toString(),
l = 0, r = s.length - 1,
sum = [];
if (s.length <= 2) return n;
while (l < r) sum.push(+s[l++] + +s[r--]);
if (l === r) sum.push(s[l]);
return add(+sum.join(''));
}
console.log(add(1234567));
I want to check whether a number (7) is divisible by another number (5), If the number is divisible by the number then I need to return the same number. If the number is not divisible by another number I need to make it divisible and return the updated value.
var i =7;
if (i % 5 == 0) {
alert("divisible by 5");
} else {
alert("divisible not by 5");
}
Here if the condition satisfy then I need to return the same value. If the condition is not satisfied I need to add the required number and make it next divisible. (Like 7 is not divisible by 5 so I need add 3 to 7 and return the value 10 which is divisible by 5).
Are there any Math functions exists to implement the same?
What you want, it seems like, is this:
function roundTo(n, d) {
return Math.floor((n + d - 1) / d) * d;
}
For n 10 and d 5, you get 10 back. For n 7 and d 5, you also get 10. What the code does is add one less than the divisor to the input number, and then divides by the divisor. It then gets rid of any fractional part (Math.floor()) and multiplies by the divisor again.
You can do that by using a simple while loop:
function doThat(number, divider) {
while(number % divider !== 0) {
number++;
}
return number;
}
doThat(12, 5); // => returns 15
Here's a fiddle: https://jsfiddle.net/rdko8dmb/
You could use this algorithm:
i % n = r, where i = 7, n = 5, and r = 2.
Then, make i = i + (n - r). i.e. i = 7 + (5-2) → 10. Then you can use this for your division.
Try this
function divisible(dividend, divisor){
if (dividend % divisor == 0) {
return dividend;
} else {
var num = dividend + (divisor-(dividend % divisor));
return num;
}
}
var res = divisible(7, 5);
console.log(res);
Here is the fastest and cleanest way to do that:
function shift(number, divider)
{
return number + (divider - (number % divider)) % divider;
}
It takes number and moves it up by the difference from (our unit) divider to the remainder to make it divisible by the divider. The % divider makes sure that if there is no difference number doesn't get pushed up by a full unit of the divider.
I do not know if this will work for all numbers... But you might try this
7 % 5 = 2. If you subtract 2 from 5 you will get 3... This is the number you need to add to 7. 16 % 5 = 1 subtract 1 from 5 = 4 .. 4 + 16 = 20
Another example 16 % 13 = 3 ... 13-3 = 10 16+10 = 26 26/13 = 2
Here's an example of function that finds next higher natural number that is divisble by y
https://www.jschallenger.com/javascript-basics/find-next-higher-number
Option 1
while (x % y !== 0) x++;
return x;
}
Option 2
if(x % y == 0){
return x;
}
else{
for(i = x+1; i > x; i++){
if(i % y == 0){
return i;
}
}
}