while multiplying two number and storing into that number ends up with a result of NaN - javascript

while iam using the += operator the multiplication results in NaN
convertToDecimal(){
let current=this.head;
let size=this.size;
size-=1;
var result;
while(current!=null){
let num=current.value;
var power=Math.pow(2,size)
result=(power*num);
size-=1;
current=current.next;
}
// console.log(result);
}
**console without putting += for result
value of result in each iteration
8
4
2
1
but afer i puts +=
result+=(power*num);
output is
NaN
NaN
NaN
NaN
Anyone can explain this please, I am new to javaScript so may be its a dumb question

This happens because your result variable has no initial value and so it starts as undefined. The first time you then execute +=, it tries to add a number to undefined which results in NaN.
Your problem can be reproduced with this simplified code:
var result;
for (let i = 0; i < 4; i++) {
result += 1;
console.log(result);
}
So initialise as var result = 0.
var result = 0;
for (let i = 0; i < 4; i++) {
result += 1;
console.log(result);
}

Related

How to get value of a variable?

I am trying to figure out a script that adds 1 each time it runs to a variable, then console logs the total amount of times.
for (let i = 1; i <= limitFizzBuzz; i++) {
// Count the FizzBuzzes
let amountOfFizzBuzzes;
amountOfFizzBuzzes = amountOfFizzBuzzes += 1;
console.log(amountOfFizzBuzzes);
}
When I tried to run this in a loop, I get:
What am I doing wrong here?
First, a simpler version of the first problem:
let num;
num += 1;
console.log(num);
num += 1 is a correct statement that adds 1 to the value of num and stores the result back in num.
console.log(num); is a correct statement that writes the value of num to the console.
But let num; doesn’t give a starting value for num. When a variable isn’t initialized to a value in JavaScript, it gets the value undefined. Doing math on undefined as if it were a number results in NaN, which is what you see.
So, a fixed version of the simpler code gives an initial value to num, like zero:
let num = 0;
num += 1;
console.log(num);
The next issue is scope. If you declare a variable inside the loop, it’s a new variable each time around. Instead, you want to use the same variable for every iteration, and have it keep its value, so move the declaration outside:
let amountOfFizzBuzzes = 0;
for (let i = 1; i <= limitFizzBuzz; i++) {
amountOfFizzBuzzes += 1;
console.log(amountOfFizzBuzzes);
}
first you Define a var let amountOfFizzBuzzes; inside a loop so that should be outside the loop
second if you need to increment a number this is a right way to do it
let amountOfFizzBuzzes=0;
for (let i = 1; i <=limitFizzBuzz; i++) {
// Count the FizzBuzzes
amountOfFizzBuzzes+= 1;
console.log(amountOfFizzBuzzes);
}
.
.
//....
limitFizzBuzz = 5;
//if you want to start from zero & increment it X times
let amountOfFizzBuzzes = 0;
for (let i = 1; i <= limitFizzBuzz; i++) {
// Count the FizzBuzzes
amountOfFizzBuzzes += 1;
console.log(amountOfFizzBuzzes);
}
#Morrison is absolutely correct.
Just initialize your amountOfFizzBuzzes above the for loop.
let amountOfFizzBuzzes =0;
for (let i = 1; i <= 10; i++) {
// Count the FizzBuzzes
amountOfFizzBuzzes++;
//amountOfFizzBuzzes +=1;
console.log(amountOfFizzBuzzes);
}

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.

the if statement condition logic

I am in need of help in this script. I am trying to write a program, where each array element is assign to a "point". I concated all the arrays and assigned it to a variable. The array runs through an if statement to tally up the score.
For this instance, I am trying to get a total of 6. However, when I run the program I am getting "2" rather than "6" in the console log. How should I write my if condition to get the result of 6?
var zero = [1,2,3,5,7]; // 0
var one = [0,4,6,9]; // 1
var two = 8; //2
function calculate(){
var NUMBERS = zero.concat(one,two);
var TOTAL = 0; // 6
for(var i = 0; i < NUMBERS.length; i++){
if(NUMBERS[i] === one[i]){
TOTAL += 1;
}else if(NUMBERS[i] == two){
TOTAL +=2;
}else {
TOTAL += 0;
}
}
console.log(TOTAL);
}
calculate();
This will only match if the value in NUMBERS[i] is in the same position of the array one.
if(NUMBERS[i] === one[i]){
Change it to this:
if (one.indexOf(NUMBERS[i]) !== -1){
to test for the presence of NUMBERS[i] in one.
Also, you have a four in both the zero and one array.
As #TJCrowder mentioned - the answer is seven.
You can omit:
TOTAL += 0
Adding zero doesn't change anything.

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.

Javascript Euler Fibonacci for loop

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

Categories