Javascript Euler Fibonacci for loop - javascript

I'm doing the Euler project problem 2 in which the objective is to sum the even numbers of the fibonacci sequence that have a value of less than 4 million. I've searched a bit and I've seen several solutions using a while loop but nothing simple using a for loop. I'm curious why I'm returning zero with the following code:
var array = [];
array[0] = 0;
array[1] = 1;
var total = 0;
for(var i=2;total<=4000000;i++) {
array[i] = array[i-1] + array[i-2];};
for(var x=0;x<array.length;x++){
if(array[x]%2 === 0){
total += array[x]};};
alert(total);
I'm guessing the problem is in my for loop using the total variable. I couldn't get it to work using array[i]<=4000000 either and I'm really curious behind the why here. Anyone know why this is? What can I change in the for loop condition (second statement) to get a correct total here?

First of all there is an infinite loop at first for. Your condition must be array[i-1] < 4000000. After that your second for loop will find the correct result.
Also for the problem, you don't need to store all fibonacci numbers then find sum of even numbers.
You can calculate sum when calculating fibonacci.
var first = 0;
var second = 1;
var sum = 0;
for(var current=first+second; current < 4000000; current = first+second){
if(current%2 === 0){
sum+=current;
}
first = second;
second = current;
}

I fixed it for you.
var i, data = [ 0, 1 ], total = 0;
for (i = 2; i <= 4000000; i++)
{
data[i] = data[i - 1] + data[i - 2];
if (data[i] % 2 === 0)
{
total += data[i];
}
}
alert(total);
I'm not sure what you termination condition should be like, you say have a value of less than 4 million, but this is ambiguous. Maybe it should be total <= 4000000 or data[i] <= 4000000. Your phrasing is not precise enough.

Sorry but for me your code going in a dead loop. first "for" use total as check but it's never incremented. If you want This is a solution for fibonacci sequence based on dinamic programming with memoization tecnic.
var f1 = 1;
var f2 = 1;
for(var i = 2; i < 40000; i++){
console.info(i, f1, f2);
var temp = f1 + f2;
f1 = f2;
f2 = temp;
}
alert(f2);

Related

JavaScript neglecting the else statement

I created a function which takes in two values..
Both are numbers represented by n & p. What the function does is that it gets the number n and splits it up then squares it to the value of p and sums them in an increasing order like this: n^p + n^(p+1) + n^(p+2) + ...
Here is the function
function digPow(n, p) {
// ...
let num = n.toString();
let pow = p;
let arrn = [];
let arrp = [];
for (let i = 0; i < num.length; i++) {
arrn.push(JSON.parse(num[i]));
}
let index = arrn.join('');
let sindex = index.split('');
for (let j = 0; j < sindex.length; j++) {
let power = p + j;
let indexs = sindex[j];
let Mathpow = Math.pow(indexs, power);
arrp.push(Mathpow);
}
let total = 0;
for (let m in arrp) {
total += arrp[m]
}
let secondVal = total / n;
let totals = total / secondVal;
let mx = [-1]
if (totals.length == n.length) {
return secondVal
} else {
return -1
}
}
Now i created variables and arrays to store up the values and then the if part is my problem.. The if/else statement is meant to let the program check if a particular variable totals is equal to n which is the input.. if true it should return a variable secondVal and if not it should return -1..
So far its only returning secondVal and i'snt returning -1 in cases where it should like:
digPow(92, 1) instead it returns 0.14130434782608695
What do i do?
totals and n are both numbers. They don't have a .length property, so both totals.length and n.length evaluate to undefined. Thus, they are equal to each other.
There are plenty of other weird things going on in your code, too. I'd recommend finding a good JavaScript tutorial and working through it to get a better feel for how the language (and programming in general) works.
Let's start by stripping out the redundant variables and circular-logic code from your function:
function digPow(n, p) {
let num = n.toString();
// let pow = p; // this is never used again
// let arrn = []; // not needed, see below
// let arrp = []; // was only used to contain values that are later summed; can instead just sum them in the first place
// this does the same thing as num.split(''), and isn't needed anyway:
//for (let i = 0; i < num.length; i++) {
// arrn.push(JSON.parse(num[i]));
//}
// this is the same as the original 'num' variable
// let index = arrn.join('');
// This could have been num.split(), but isn't needed anyway
// let sindex = index.split('');
let total = 0; // moved this line here from after the loop below:
for (let j = 0; j < num.length; j++) { // use num.length instead of the redundant sindex
let power = p + j;
// The only reason for the sindex array was to get individual characters from the string, which we can do with .charAt().
//let indexs = sindex[j];
let indexs = num.charAt(j);
let Mathpow = Math.pow(indexs, power);
//arrp.push(Mathpow); // No need to collect these in an array
total += Mathpow; // do this instead
}
// No need for this loop, since we can sum the total during the previous loop
// let total = 0;
//for (let m in arrp) {
// total += arrp[m]
//}
let secondVal = total / n;
// let totals = total / secondVal;
// The above is the same thing as total / total / n, which is:
let totals = 1/n;
// This is never used
//let mx = [-1]
// This was totals.length and n.length, which for numbers would always be undefined, so would always return true
if (totals == n) {
return secondVal
} else {
return -1
}
}
So the above reduces to this functionally identical code:
function digPow(n, p) {
let num = n.toString();
let total = 0;
for (let j = 0; j < num.length; j++) {
let power = p + j;
let indexs = num.charAt(j);
let Mathpow = Math.pow(indexs, power);
total += Mathpow;
}
let secondVal = total / n;
let totals = 1 / n;
if (totals == n) {
return secondVal
} else {
return -1
}
}
Now let's talk about the logic. The actual output will always be -1, unless the input is 1, due to what's clearly a logic error in the totals variable: the only case where 1/n == n is true is when n==1.
Setting that aside, and looking only at the secondVal variable, some examples of what it's calculating for a given input would be
digPow(123,1) --> (1^1 + 2^2 + 3^3) / 123 --> 14/123
digPow(321,2) --> (3^2 + 2^3 + 1^4) / 321 --> 21/321
digPow(92, 1) --> (9^1 + 2^2) / 92 --> 13/92
I'm pretty sure from your description that that's not what you intended. I'm not at all sure from your description what you did intend, so can't be much help in correcting the function beyond what I've done here.
What I'd suggest is to sit down and think through your algorithm first; make sure you know what you're trying to build before you start building it. There were some syntax problems with your code, but the real issues are with the logic itself. Your original function shows clear signs of "just keep throwing more lines of code at it until something happens" rather than any planned thinking -- that's how you wind up with stuff like "split a string into an array, then join it back into a string, then split that string into another array". Write pseudocode first: break the problem down into steps, think through those steps for some example inputs and make sure it'll produce the output you're looking for. Only then should you bust out the IDE and start writing javascript.

How to Create a For-Loop that calculates 6Factorial

To do this you must multiply 6*5*4*3*2*1. To verify your loop is working correctly, the value you are looking for as a result is: 720
var dvDDG = document.querySelector("#ddg");
for(var i = 0; i < 7; i++) {
//remainder..
if( (i*7) == 720 ) {
dvDDG.innerHTML += i + "<br />";
}
}
I'm not entirely certain what you're trying to do with the code you have, it will simply check all numbers zero through six inclusive, and output the value which, when multiplied by seven, is equal to 720.
Since the highest value you'll get is 6 x 7 = 42 (nowhere near 720), you'll see nothing.
The pseudo-code for what you're after would be along the lines of:
fact = 1
for i = 2 to N inclusive:
fact = fact * i
print fact
Turning that into Javascript (or any procedural language for that matter) should be fairly simple, such as with:
function fact(n) {
res = 1
for (var i = 2; i <= n; i++) {
res = res * i;
}
return res
}
alert(fact(6))
It's fairly simple:
var factorial = 1;
var num = 6;
for (var i = 1; i <= num; i++){
factorial *= i;
}
There you go, your answer is the variable factorial. Just copy it into any output function you want. Be careful though, factorial can get pretty huge very fast. Try not to experiment on numbers that much larger that 6.

Perfect squares from odd numbers

In JavaScript, is there a more efficient way of calculating perfect squares working from odd numbers than this (the last perfect square stored in the array perfectSqrs is console.logged):
let n = 999,
oddNums = [],
i;
for (i = 3; i < n; i += 1) {
if (i % 2 !== 0) {
oddNums.push(i);
}
}
let oddLength = oddNums.length;
let perfectSqrs = [1],
j = 0;
while (j < oddLength - 1) {
perfectSqrs[j + 1] = perfectSqrs[j] + oddNums[j];
j += 1;
}
console.log(perfectSqrs[perfectSqrs.length - 1]);
Looks like you just want to generate an array of perfect squares? Perhaps you can do something like this:
var squares = [1];
var numSquares = 100;
for (var i=3; i<numSquares*2; i+=2) {
squares.push(squares[squares.length - 1] + i);
}
console.log(squares);
For people unclear about this algorithm, basically:
1
4 (1+3)
9 (1+3+5)
16 (1+3+5+7)
25 (1+3+5+7+9)
Perfect square is essentially the sum of odd numbers
Nothing to do with JS more with algorithms and logic. You can totally avoid the first loop and also avoid storing (memory efficiency) odd numbers. Start your second loop with 1 and iterate by incrementing by 2 instead of 1 (1,3,5,7,...).

Why does my code work with underscore.js but not when I use Ramda.js?

I am new to Javascript, I am doing a coding challenge to learn more about the language. This is not school related or anything like that, totally for my own personal growth. Here is the challenge:
Return the sum of all odd Fibonacci numbers up to and including the
passed number if it is a Fibonacci number.
I have spent the past 2 evenings working on solving this challenge. When I run my code using underscore.js it works. When I use Ramda.js it says NaN. I would think both would return NaN. I'm very surprised that I can get the correct answer from one and not the other. Any insights would be greatly appreciated!
var R = require('ramda');
function sumFibs(num) {
var fib_Arr = [];
var new_Arr = [];
var total = 0;
// I use this to tell if the fib num is greater than 2
var the_Bit = "false";
// This is used to keep track of when to stop the loop
var fib_Num = 0;
// THIS WORKS FROM HERE
// This loop generates a list of fibonacci numbers then pushes them to the fib_Arr
for(var i = 0; total < num; i++){
if (i < 1){
fib_Arr.push(0);
}
else if (i === 1){
fib_Arr.push(i);
fib_Arr.push(1);
}
else if (i === 2){
fib_Arr.push(2);
the_Bit = "true";
}
else if (the_Bit === "true"){
temp_Arr = R.last(fib_Arr,2);
temp_Arr = temp_Arr[0] + temp_Arr[1];
fib_Arr.push(temp_Arr);
total = R.last(fib_Arr);
}
// Generating the fib Array works TO HERE!!!!
}
// console.log(fib_Arr); // Print out the generated fibonacci array
// if last Array element is greater than the original in
var last_Element = R.last(fib_Arr);
if (last_Element > num){
console.log("The last element of the array is bigger!");
fib_Arr.splice(-1,1); // This removes the last item from the array if it is larger than the original num input
}
// This loop removes all of the EVEN fibonacci numbers and leaves all of the ODD numbers
for (var j = 0; j < fib_Arr.length; j++){
if (fib_Arr[j] % 2 !== 0){
new_Arr.push((fib_Arr[j]));
}
}
// This checks if the original input num was a
if (num % 2 !== 0){
new_Arr.push(num);
}
else{
console.log("The original num was not a Fibonacci number!");
}
// if last Array element is the same as the original input num
var last = R.last(fib_Arr);
if (last === num){
console.log("Removing the last element of the array!");
new_Arr.splice(-1,1); // This removes the last item from the array if it is the same as the original num input
}
// Now to add all of the numbers up :-)
for (var k = 0; k < new_Arr.length; k++){
console.log("This is fib_Num: " + fib_Num);
// console.log(fib_N`);
fib_Num = fib_Num += new_Arr[k];
}
return fib_Num;
}
// TEST CASES:
// console.log(sumFibs(75025)); //.to.equal(135721);
console.log(sumFibs(75024)); //.to.equal(60696);
You have a problem on these lines :
temp_Arr = R.last(fib_Arr,2);
temp_Arr = temp_Arr[0] + temp_Arr[1];
Besides the fact that R.last does not take a second argument (that will not fail though), you are using temp_arr as an array, when it is a number. Therefore, temp_arr gets a NaN value.
You are probably looking for R.take (combined with R.reverse) or R.slice.
By changing :
temp_Arr = R.last(fib_Arr,2);
with :
temp_Arr = R.take(2, R.reverse(fib_Arr));
or with :
temp_Arr = R.slice(fib_Arr.length - 2, fib_Arr.length)(fib_Arr);
or with (bonus play with a reduce from the right) :
temp_Arr = R.reduceRight(function(arr, elem) {
return arr.length < 2 ? [elem].concat(arr) : arr;
}, [])(fib_Arr);
We get :
sumFibs(75024) === 60696
For the record, here's how you do this problem:
function fibSumTo(n) {
var f1 = 1, f2 = 1, sum = 1, t;
while (f2 <= n) {
if (f2 & 1) sum += f2;
t = f1 + f2;
f1 = f2;
f2 = t;
}
return sum;
}
There's really no need for any sort of library because there's really no need for any sort of data structure.
var _ = require('underscore');function sumUpFibs (number){
arr_of_fibs = [1,1];
current = 1; //cursor for previous location
while (true){
var num = arr_of_fibs[current] + arr_of_fibs[current - 1];
if (num <= number) {
arr_of_fibs.push(num);
current++;
} else {
break;
}
}
console.log(arr_of_fibs);
var total = 0;
_.each(arr_of_fibs, function(fib){
total += fib;
})
return total;}console.log(sumUpFibs(75025));
This may be a better implementation... Though I know you're just starting so I don't want to come off as mean : D.... Also, maybe check your test cases too.

How to store the result of each iteration of a for loop into an array (Javascript)

This question could also be (depending on how you look at it) - How to use a for loop to do a basic math operation that adds up the sum of the multiples of 3
So I am doing Problem 1 of Project Euler.
I've (already) hit a steel-reinforced wall. I could use some help - with just a specific portion of the problem please (I am not looking for just an answer to the problem, but rather, an answer to my specific problem so I can carry on with trying to solve the remainder problem using any answer you guys provide me here)...
Anyways.
I (think I) created a for loop that will give me the multiples of 3. However, I'm trying to store the result of each iteration of the for-loop so that it adds up to the sum of those multiples i.e. I'm trying to store the result from each iteration of the loop - whether it be into an array or into a variable that takes the sum of the multiples - it doesn't matter to me - I wouldn't mind learning both methods.
I'm sure this sounds kind of confusing so let me paint my picture w/ an example...
I have a for-loop:
for (i = 1; i <= 3; i++) {
var x = 0;
x += (i * 3);
WHAT DO I DO NEXT????
^ So I would think that this gives me x with a value of 3 upon the 1st iteration of the loop, x with a value of 9 on the 2nd loop, and x with a value of 18 on the final loop. That's correct, right? (if this were returning 18 I don't think I would need to store the values of each iteration into an array)
1st iteration:
i = 1; x = 0
Original equation...
(i * 3) + x
So...
(1 * 3) + (x = 0) = 3
So after completion of the 1st loop, x has a value of 3, right???
(Question: How would I store this value of x (which is 3) - how would I store it in an array while in this stage of the for loop?)
2nd iteration of loop:
i = 2; x = 3
(2 * 3) + (x = 3) = 9
(same question as before: how would I add this value to an array?)
3rd iteration:
i = 3; x = 9
(3 * 3) + (x = 9) = 18
Q: shouldn't this be the final value of x upon completion of the for loop??? For some reason, when I run the code, the final value of x is 9, and not 18
So, basically I am trying to add the sum of the 3 values...But what do I do next? I thought my for loop would add the result of the equation after each loop to x, but instead of ending up w/ 18 (the sum of 3 + 6 + 9), x's value was 9???
Should I use an array? If so, I'm thinking I could add the return value to an array, but I'm not sure how to add the result of each iteration of the loop to an array. Maybe the following?...
for (i = 1; i <= 3; i++) {
var array = [];
x = 0;
x += (i *3);
array.push(x);
};
^ I tried running that in jfiddle, but it would only add the last value of x (9) into the array... So how would I add the value of x to an array after each iteration of the for loop??? And I'm not seeing what's wrong with my for-loop to where it's returning a value of x as 9?
Also, I'm assuming the euler problems get significantly more difficult as we progress? If so, I've got a TON of work/practice to do....
THANKS IN ADVANCE...
Just create the array once, and push the result at each iteration to the array:
var array = [];
for (i = 1; i <= 3; i++) {
var x = 0;
x += (i *3);
array.push(x);
}
Or for that matter, just use this:
var array = [];
for (i = 1; i <= 3; i++) {
array.push(i *3);
}
Or to simply get the sum of the factors, use this:
var x = 0;
for (i = 1; i <= 3; i++) {
x += i *3;
}
You are declaring var x = 0 and var array = [] at every step of the loop, try something like:
var array = [], x = 0;
for (i=1; i<4; i++){
x += (i*3);
array.push(x);
}
You can use like this:
and you have to define X out of the loop
var array = [],
x = 0;
for (i=1; i<4; i++){
x += (i*3);
array.push(x);
}

Categories