i have to solve the following function: "x" represent a number of cycles. One cycle sums +1 and then multiply the result *2. For example:
0 cycles = 0 + 1 = 1 (result)
1 cycles = 1 * 2 = 2 (result)
2 cycles = 2 + 1 = 3 (result)
3 cycles = 3 * 2 = 6 (result)
4 cycles = 6 + 1 = 7 (result) and so on.
I have this function:
function final(x) {
for (var i = 0; i < x; i++) {
var result = x[i] * 2 + 1
}
return result;
}
Can you help me out?
If you want to store the results, you can use answer by #Kornflexx. If not, you can directly calculate the value :
function final (x) {
var t = (4 << (x / 2)) - 2;
return x % 2 ? t : t / 2;
}
Note that if x is large you will quickly pass the int limit and would then need to deal with big integers
This should work if you don't care of the fact that the for start at 1.
function final(x) {
var result = [];
result[0] = 1;
for (var i = 1; i < x; i++) {
result[i] = i % 2 ? result[i - 1] * 2 : result[i - 1] + 1;
}
return result;
}
If you only require the final result of the function then the following will achieve that for you.
function final(x) {
var result = 0;
for (var i = 0; i < x; i++) {
if (x % 2 === 0) {
result = result + 1;
} else {
result = result * 2;
}
}
return result;
}
Thanks for your help, the solution finally was this:
function final(x){
var result = 0;
for (var i = 0; i < x; i++){
if (i % 2 === 0){
result = result * 2 + 1;}
else{
result = (result + 1);}
}
return result+1;
}
Just for variety, you can have this short form
function final(x) {
var result = 0;
for (var i = 0; i < x; i++) {
result = x % 2 == 0 ? result + 1 : result * 2
}
console.log(x,result)
return result;
}
final(3)
Related
Here's the code i wrote to solve the problem:
let isPrime = function(n) {
for (let i = 2; i < n; i++) {
if (n % i === 0) {
return false;
}
}
return true;
};
function nextPrime(num) {
let newNum = num;
for (let i = 0; i < newNum; i++) {
if (!isPrime(newNum)) {
newNum += 1;
} else if (isPrime(newNum)) {
return newNum;
}
}
};
My plan is:
// increment the num by 1 and check if that new num is prime;
// if not, increment again and check again. Repeat the process untill prime is found.
Input and (expected output is commented):
console.log(nextPrime(2)); // 3
console.log(nextPrime(3)); // 5
console.log(nextPrime(7)); // 11
console.log(nextPrime(8)); // 11
console.log(nextPrime(20)); // 23
console.log(nextPrime(97)); // 101
The output i'm getting;
2
3
7
11
23
97
I'd like to know where exactly my implementation is wrong. Also, i'd like the code to be without fancy methods because i'm new to all this. Thank you!
The assignment newNum = num precisely does not make newNum a new number, but the same ! This is why the function returns immediately when the input argument is prime.
By the way, the loop would be much cleaner as
do
{
newNum += 1;
} while (!isPrime(newNum));
function nextPrime(previousPrime) {
const value = previousPrime;
if (value > 2) {
var i, q;
do {
i = 3;
value += 2;
q = Math.floor(Math.sqrt(value));
while (i <= q && value % i) {
i += 2;
}
} while (i <= q);
return value;
}
return value === 2 ? 3 : 2;
}
I have created a function that sumbs up all odd fibronacci numbers up to a given number, and for the most part it works all for except one number. For example sumFibs(10) should return 10 becuz all Fib #s <= 10 are 1,1,3 and 5.
If I do sumFibs(75024); I get 135721 instead of the expected value is 60696. For every other number it works perfectly and am scratching my head to solve it
function sumFibs(num) {
let thunderAss = [];
let currDmp = 0;
let nxtRmp = 1;
var pushNxt = 0;
// push into array
for (let x = 0; x < num; x++) {
if (x <= 1) {
console.log("lets go");
thunderAss.push(1); // 2l almond milk
} else {
thunderAss.push(thunderAss[x - 1] + thunderAss[x - 2]);
console.log(x, " x is factor");
}
}
console.log(thunderAss);
let cuntNuts = 0;
for (let x = 0; x < num; x++) {
if (cuntNuts < num) {
if (thunderAss[x] % 2 == 0) {} else {
cuntNuts += thunderAss[x];
}
} else {
break;
}
}
console.log("CN: ", cuntNuts);
return cuntNuts;
}
sumFibs(75024); // 60696 but 135721
sumFibs(4);
The condition if (cuntNuts < num) is wrong. cuntNuts is the sum of fibonacci numbers, not the fibonacci number itself. So you're stopping when the sum reaches n, not summing all the odd numbers up to n.
You should be comparing thunderAss[x] with num. And it should be <= if that number should be included in the total.
You can also put this condition into the for loop header rather than adding it as a separate check in the body.
function sumFibs(num) {
let thunderAss = [];
let currDmp = 0;
let nxtRmp = 1;
var pushNxt = 0;
// push into array
for (let x = 0; x < num; x++) {
if (x <= 1) {
console.log("lets go");
thunderAss.push(1); // 2l almond milk
} else {
thunderAss.push(thunderAss[x - 1] + thunderAss[x - 2]);
console.log(x, " x is factor");
}
}
console.log(thunderAss);
let cuntNuts = 0;
for (let x = 0; thunderAss[x] <= num; x++) {
if (thunderAss[x] % 2 == 0) {} else {
cuntNuts += thunderAss[x];
}
}
console.log("CN: ", cuntNuts);
return cuntNuts;
}
sumFibs(75024); // 60696 but 135721
sumFibs(4);
You are adding the num first Fibonacci numbers instead of the Fibonacci numbers less than or equal to num.
In my solution here, I do the correct thing and get the correct answer:
function* fibonacci()
{
let x = 0;
let y = 1;
while (true) {
yield x;
[x, y] = [y, x+y];
}
}
function sum_odd_fibonacci(max)
{
const fib_seq = fibonacci();
let s = 0;
let n;
while ( (n=fib_seq.next().value) <= max) {
if (n % 2 == 1) {
s += n;
}
}
return s;
}
console.log(sum_odd_fibonacci(75024));
I am stuck in summing up to number 10. Can't get it right.
What i am getting is the total sum from 10 digits (after filtering odd only 7). Where should i make <= num ?
function sumFibs(num) {
var fib = [1, 1];
for (var i = 2; i < num; i++) {
var next = fib[i - 1] + fib[i - 2];
var fibi = fib.push(next);
}
return fib.filter(function(a) {
return (a % 2 != 0);
})
.reduce(function(a, z) {
return a + z;
})
}
console.log(sumFibs(10));
Expected output 10, but getting 99
Add a < num to your filter callback test, so you get a % 2 && a < num
function sumFibs(num) {
var fib = [0, 1];
for (var i = 2; i < num; i++) {
var next = fib[i - 1] + fib[i - 2];
var fibi = fib.push(next);
}
return fib.filter(function (a) {
return a % 2 && a < num;
}).reduce(function (a, z) {
return a + z;
}, 0);
}
console.log(sumFibs(0))
console.log(sumFibs(1))
console.log(sumFibs(10))
console.log(sumFibs(9000))
You don't need to use array at all if you need only sum of those numbers
function sumFibs(num) {
if(num <= 1) return 0;
var a = 0, b = 1, sum = a + b;
while(true) {
var next = a + b;
if(next >= num) {
break;
}
if(next % 2) {
sum += next;
}
a = b;
b = next;
}
return sum
}
console.log(sumFibs(0))
console.log(sumFibs(1))
console.log(sumFibs(10))
console.log(sumFibs(9000))
You need to change the loop condition. Loop till the last value of fib is less than num
function sumFibs(num) {
var fib = [1, 1];
for (var i = 2; fib[fib.length - 1] < num; i++) {
var next = fib[i - 1] + fib[i - 2];
fib.push(next);
}
return fib
.filter(x => !(x % 2))
.reduce((ac,a) => ac + a,0)
}
console.log(sumFibs(10));
If you want to retain your code for the most part, you can add an if statement that breaks the loop once your next number goes beyond your num:
function sumFibs(num) {
var fib = [1, 1];
for (var i = 2; i < num; i++) {
var next = fib[i - 1] + fib[i - 2];
if ( next > num ) { // not >= assuming you want to include your num
break;
}
fib.push(next);
}
console.log({fib});
return fib.filter(function(a) {
return (a % 2 != 0);
})
.reduce(function(a, z) {
return a + z;
})
}
console.log(sumFibs(10));
Your code is summing the first N Fibonacci numbers that are odd. You seem to be looking for the first odd Fibonacci numbers that sum to N:
function oddFibsThatAddTo(target)
{
let currentFib = 1;
let lastFib = 1;
let sum = 2;
const outs = [1,1];
while(sum < target)
{
let nextFib = currentFib + lastFib;
if(nextFib % 2 == 1)
{
sum += nextFib;
outs.push(nextFib);
}
lastFib = currentFib;
currentFib = nextFib;
}
if(sum > target)
{
throw 'can\'t find perfect sequence';
}
return outs;
}
console.log(oddFibsThatAddTo(10))
function sumFibs(num) {
var fib=[1,1];
for(var i=2; i<num; i++){
var next=fib[i-1]+fib[i-2];
var fibi=fib.push(next);
}
return fib.filter(function(a){
return(a%2!=0 && a<=num);
})
.reduce(function(a,z){
return a+z;
})
}
console.log(sumFibs(10));
I am working on this kata https://www.codewars.com/kata/count-9-s-from-1-to-n/train/javascript
and i have written this code for it, but its not working. This question is similar to this one Count the number of occurrences of 0's in integers from 1 to N
but it is different because searching for 9's is practically very different to searching for 0's.
think part of the problem with this code is that it takes too long to run...
any advice appreciated!
function has9(n) {
var nine = [];
var ninearr = n.toString().split('');
for (var j = 0; j < ninearr.length; j++) {
if (ninearr[j] == '9') {
nine.push(ninearr[j]);
}
}
return nine.length;
}
function number9(n) {
var arr = [];
var arrnew = [];
for (var i = 0; i <= n; i++) {
arr.push(i);
}
for (var l = 0; l < arr.length; l++) {
arrnew.push(has9(l));
}
var sum = arrnew.reduce((a, b) => a + b, 0);
return sum;
}
Why not a regex based solution? (Too slow as well?)
const count9s = num => num.toString().match(/9/g).length
console.log(count9s(19716541879)) // 2
console.log(count9s(919191919191919)) // 8
console.log(count9s(999)) // 3
console.log(count9s(999999)) // 6
I have taken the above hint and completely re written the code, which I now feel should work, and it does for most inputs, but codewars is saying it fails on some of them. any ideas why?
function nines(n){
if(n>=100){
var q= Math.floor(n/100);
var nq= q * 20;
var r = (n%100);
var s = Math.floor(r/9);
if (r<=90){
return s + nq;
}
if (r == 99){
return 20 + nq;
}
if (90 < r < 100 && r!= 99){
var t = (r-90);
return nq + s + t;
}
}
if (n<100){
if (n<=90){
var a = Math.floor(n/9);
return a ;
}
if (n == 99){
return 20
}
if (90 < n < 100 && n!= 99){
var c = (n-90);
return 10 + c;
}
}
}
=== UPDATE ===
I just solved your kata using
function number9Helper(num) {
var pow = Math.floor(Math.log10(num));
var round = Math.pow(10, pow);
var times = Math.floor(num / round);
var rest = Math.abs(num - (round * times));
var res = pow * (round==10 ? 1 : round / 10) * times;
if (num.toString()[0] == '9') res += rest;
if (rest < 9) return res;
else return res + number9Helper(rest);
}
function number9(num) {
var res = number9Helper(num);
res = res + (num.toString().split('9').length-1);
return res;
}
== Function below works but is slow ===
So, could something like this work for you:
for (var nines=0, i=1; i<=n; i++) nines += i.toString().split('9').length-1;
Basically, there are many way to achieve what you need, in the end it all depends how do you want to approach it.
You can test it with
function nines(n) {
for (var nines=0, i=1; i<=n; i++) nines += i.toString().split('9').length-1;
return nines;
}
function number9(n) {
if (n < 8) {
return 0
};
if (n === 9) {
return 1
};
if (n > 10) {
let str = ''
for (let i = 9; i <= n; i++) {
str += String(i)
}
return str.match(/[9]/g).length
}
}
https://codepen.io/aholston/pen/ZJbrjd
The codepen link has commented code as well as actual instructions in HTML
Otherwise.... what I ultimately have to do is write a function that takes two params(a and b) and takes all the numbers between those two params (a-b) and put every number that can be added to the consecutive fowers and be equal to that number into a new array. Ex: 89 = 8^1 + 9^2 = 89 or 135 = 1^1 + 3^2 + 5^3 = 135
function sumDigPow(a, b) {
// Your code here
var numbers = [];
var checkNum = [];
var finalNum = [];
var total = 0;
for (var i = 1; i <= b; i++) {
if (i >= a && i <= b) {
numbers.push(i);
}
}
for (var x = 0; x < numbers.length; x++) {
var checkNum = numbers[x].toString().split('');
if (checkNum.length == 1) {
var together = parseInt(checkNum);
finalNum.push(together);
} else if (checkNum.length > 1) {
var together = checkNum.join('');
var togNumber = parseInt(together);
for (var y = checkNum.length; y > 0; y--) {
total += Math.pow(checkNum[y - 1], y);
}
if (total == togNumber) {
finalNum.push(togNumber);
}
}
}
return finalNum;
}
try this:
function listnum(a, b) {
var finalNum = [];
for (var i = a; i <= b; i++) {
var x = i;
var y = i;
var tot = 0;
j = i.toString().length;
while (y) {
tot += Math.pow((y%10), j--);
y = Math.floor(y/10);
}
if (tot == x)
finalNum.push(i);
}
return finalNum;
}
console.log(listnum(1, 200));
Okay, after debugging this is what I learned.
for (var y = checkNum.length; y > 0; y--) {
total += Math.pow(checkNum[y - 1], y);
}
if (total == togNumber) {
finalNum.push(togNumber);
}
}
}
return finalNum;
}
Everytime this loop happened, I neglected to reset the 'total' variable back to 0. So I was never getting the right answer for my Math.pow() because my answer was always adding to the previous value of total. In order to fix this, I added var total = 0; after i decided whether or not to push 'togNumber' into 'finalNum.' So my code looks like this..
for (var y = checkNum.length; y > 0; y--) {
total += Math.pow(checkNum[y - 1], y);
}
if (total == togNumber) {
finalNum.push(togNumber);}
}
var total = 0;
}
return finalNum;
}