Function in javascript is returning undefined (NaN)? - javascript

We need the code for summation of the series up to nth term in javascript :
1/(2n+1)
When I executed the function series(80); it alerted NaN.
Code:
function series(n){
var i;
var s;
for(i = 1; i <= n; i++) {
s = s + 1/(2*i+1);
}
alert(s);
}
series(80);

You could set the default value on s = 0
function series(n) {
var i;
var s = 0;
var n;
for (i = 1; i <= n; i++) {
s = s + 1 / (2 * i + 1);
}
alert(s);
}
series(80)

Here is the example and definitely worked no need to declare n because we pass it as argument in function.
function series(n) {
var i, s = 0;
for(i = 1; i <= n; i++) {
s = s + 1/(2*i+1);
}
alert(s);
}
series(80);
https://jsfiddle.net/x1ea748y/1/

Related

Why does this function return " '\'1\'' " according to codewars?

So I'm trying to solve this codewars problem (https://www.codewars.com/kata/5518a860a73e708c0a000027/train/javascript), but instead of my function returning a regular string like "1", it apparently returns something like " '\'1\'' ", according to codewars. Why is this? My code is below:
function lastDigit(as){
var product = "1";
for(var i = as.length - 1; i >= 0; i--){
var num = as[i]
//console.log(num)
//console.log(bigPower(num.toString(), product))
product = bigPower(as[i].toString(), product);
}
var prodArr = product.split("");
console.log(prodArr[prodArr.length - 1].toString());
return prodArr[prodArr.length - 1].toString();
}
function bigPower(base, exponent){
var product = base;
for(var i = 1; i < parseInt(exponent); i++){
product = multiply(product.toString(), base.toString());
}
return product;
}
function multiply(a, b) {
const product = Array(a.length+b.length).fill(0);
for (let i = a.length; i--; null) {
let carry = 0;
for (let j = b.length; j--; null) {
product[1+i+j] += carry + a[i]*b[j];
carry = Math.floor(product[1+i+j] / 10);
product[1+i+j] = product[1+i+j] % 10;
}
product[i] += carry;
}
return product.join("").replace(/^0*(\d)/, "$1");
}
Use parseInt function in the return statement to parse the string and return as an integer.
return parseInt(prodArr[prodArr.length - 1].toString());
function lastDigit(as){
var product = "1";
for(var i = as.length - 1; i >= 0; i--){
var num = as[i]
product = bigPower(as[i].toString(), product);
}
var prodArr = product.split("");
return parseInt(prodArr[prodArr.length - 1].toString());
}
function bigPower(base, exponent){
var product = base;
for(var i = 1; i < parseInt(exponent); i++){
product = multiply(product.toString(), base.toString());
}
return product;
}
function multiply(a, b) {
const product = Array(a.length+b.length).fill(0);
for (let i = a.length; i--; null) {
let carry = 0;
for (let j = b.length; j--; null) {
product[1+i+j] += carry + a[i]*b[j];
carry = Math.floor(product[1+i+j] / 10);
product[1+i+j] = product[1+i+j] % 10;
}
product[i] += carry;
}
return product.join("").replace(/^0*(\d)/, "$1");
}
console.log(lastDigit([3, 4, 2]))

Factorializing with Javascript

I made a factorial program in javascript, or at least I thought I did. When I don't make it a function it works, but when I do it doesn't, where am I going wrong?
function factorialize(num) {
var text = 1;
var i;
for (i = 1; i < num + 1; i++) {
text *= i;
}}
factorialize(5)
This above doesn't work, I also don't get any error message when I should be getting 120.
num = 5
var text = 1;
var i;
x = num;
for (i = 1; i < num + 1; i++) {
text *= i;
}
But this outputs 120, so where am I going wrong in my initial code?
You're missing the return statement inside the function.
The return statement ends function execution and specifies a value to
be returned to the function caller.
function factorialize(num) {
var text = 1;
var i;
for (i = 1; i < num + 1; i++) {
text *= i;
}
return text;
}
console.log(factorialize(5));

There's a bug in my code

My code isn't working . I'm trying to figure out what the bug is . Can someone help ? ! It's a function that is supposed to return an array of the first n triangular numbers.
For example, listTriangularNumbers(5) returns [1,3,6,10,15].
function listTriangularNumbers(n) {
var num;
var array = [];
for (i = 1; i <= n; ++i) {
num = i;
for (j = i; j >= 1; --j) {
num = num + j;
}
array.push(num);
}
return array;
}
Your initial initialization of j is wrong, it's starting at i so it's going too high. Also switched the operators around to make sure the conditions work.
function listTriangularNumbers(n) {
var num;
var array = [];
for (i = 1; i <= n; i++) {
num = i;
for (j = i-1; j >= 1; j--) {
num = num + j;
}
array.push(num);
}
return array;
}
You can try below code to get help:
a = listTriangularNumbers(8);
console.log(a);
function listTriangularNumbers(n) {
var num;
var array = [0];
for (i = 1; i <= n; i++) {
num = 0;
for (j = 1; j <= i; j++) {
num = num + j;
}
array.push(num);
}
return array;
}
You actually don't need 2 for-loops to do this operation. A single for-loop would suffice.
function listTriangularNumbers(n) {
// Initialize result array with first element already inserted
var result = [1];
// Starting the loop from i=2, we sum the value of i
// with the last inserted element in the array.
// Then we push the result in the array
for (i = 2; i <= n; i++) {
result.push(result[result.length - 1] + i);
}
// Return the result
return result;
}
console.log(listTriangularNumbers(5));
function listTriangularNumbers(n) {
var num;
var array = [];
for (i = 1; i <= n; ++i) {
num = i;
for (j = i-1; j >= 1; --j) {
num = num + j;
}
array.push(num);
}
return array;
}
var print=listTriangularNumbers(5);
console.log(print);

Binary to Decimal Javascript

This code is supposed to take in a string ("100101") and output the result in decimal.I'm not quite sure why it's not working.Any help would be appreciated.
function BinaryConverter(str) {
var num=str.split("");
var powers=[];
var sum=0;
for(var i=0;i<num.length;i++){
powers.push(i);
}
for(var i=powers.length-1;i>=0;i--){
for(var j=0;j<num.length;i++){
sum+=Math.pow(2,i)*num[j];
}
}
return sum;
};
Here's my updated code below .For an input "011" it should do( 2^2*0 +2^1*1 +2^0*1)to =3 but it returns 14.Anybody know where I'm going wrong?
function BinaryConverter(str) {
var num=str.split("");
var powers=[];
var sum=0;
for(var i=0;i<num.length;i++){
powers.push(i);
}
for(var i=powers.length-1;i>=0;i--){
for(var j=0;j<num.length;j++){
sum+=Math.pow(2,i)*num[j];
}
}
return sum;
};
The two nested for loops have a problem. The first one subtracts an i, while the second adds an i forever creating a never ending loop.
ALSO your code should be this:
function BinaryConverter(str) {
var num=str.split("");
var powers=[];
var sum=0;
var numlength=num.length;
for(var i=0;i<num.length;i++){
powers.push(i);
}
for(var i=powers.length-1;i>=0;i--){
sum+=Math.pow(2,i)*num[numlength-i-1];
}
return sum;
};
I don't think you need the nested for loop
If you don't want to do that with parseInt() for some reason (like, because the homework problem says you can't), you can do this without the complexity and expense of calling Math.pow() for each digit:
function parseBinary(str) {
var i, value = 0;
for (i = 0; i < str.length; ++i)
value = value * 2 + +str[i];
return value;
}
That doesn't check for invalid input strings.
ace040686 only inverted the pow(2,i) and num[len-1-i] in his answer, otherwise it would be correct. Also you're pushing 0..str.length-1 unnecessarily to powers, those are implicit indices.
function convertNaive(str) {
var num = str.split("");
var len = num.length;
var sum = 0;
for(var i = len - 1; i >= 0; --i)
sum += Math.pow(2, len - 1 - i) * num[i];
return sum;
}
You can improve this a bit to avoid the unnecessary array and especially Math.pow:
function convertImproved(str) {
var len = str.length;
var sum = 0;
for(var i = 0, fac = 1; i < len; ++i, fac *= 2)
sum += fac * str[len - 1 - i];
return sum;
}
Try it yourself:
var input = "100101";
var logNode = document.getElementById("log");
function log(line) {
var text = document.createTextNode(line);
var node = document.createElement("p");
node.appendChild(text);
logNode.appendChild(node);
}
function convertNaive(str) {
var num = str.split("");
var len = num.length;
var sum = 0;
for(var i = len - 1; i >= 0; --i)
sum += Math.pow(2, len - 1 - i) * num[i];
return sum;
}
function convertImproved(str) {
var len = str.length;
var sum = 0;
for(var i = 0, fac = 1; i < len; ++i, fac *= 2)
sum += fac * str[len - 1 - i];
return sum;
}
log("input: " + input);
log("parseInt(input, 2): " + parseInt(input, 2));
log("convertNaive(input): " + convertNaive(input));
log("convertImproved(input): " + convertImproved(input));
<div id="log" />
Here is the simple implementation of binary to decimal in javascript.
main();
function main() {
let binaryInput = 10000100111;
let decimalOutput = binaryTodecimal(binaryInput);
console.log(decimalOutput);
}
function binaryTodecimal(input) {
let inputString = input.toString();
let result = 0;
let exponent = 1;
let currentBit = 0;
for (let i = inputString.length - 1; i >= 0; i--) {
currentBit = parseInt(inputString[i]);
currentBit *= exponent;
result += currentBit;
exponent *= 2;
}
return result;
}

$.inArray() jQuery function

I can not figure out why this is not working, should be returning an array with four distinct values, but it doesn't
$(document).ready(function (e) {
var randomNumbers = new Array();
for (var i = 0; i < 4; i++) {
randomNumbers[i] = Math.floor((Math.random() * 9) + 1);
while ($.inArray(randomNumbers[i], randomNumbers) !== -1) {
randomNumbers[i] = Math.floor((Math.random() * 9) + 1);
}
}
for (var i = 0; i < randomNumbers.length; i++) {
if ($('#output').html() !== '') {
var existingOutput = $('#output').html();
$('#output').html(existingOutput + randomNumbers[i]);
} else {
$('#output').html(randomNumbers[i]);
}
}
});
Can cut out the if and the second loop by appending the joined array
$(document).ready(function (e) {
var randomNumbers = new Array();
for (var i = 0; i < 4; i++) {
var ran =newNum();
/* unique check*/
while ( $.inArray( ran, randomNumbers) >-1){
ran=newNum();
}
randomNumbers.push(ran)
}
$('#output').append( randomNumbers.join(''))
});
function newNum(){
return Math.floor((Math.random() * 9) + 1);
}
Alternate solution using a shuffle method ( found in this post ):
var a=[1,2,3,4,5,6,7,8,9];
function Shuffle(o) {
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
$('#output').append( Shuffle(a).splice(0,4).join(''))
If you generate a number and put it in the array, don't you think that $.inArray() will tell you so?
Your while loop is guaranteed to hang. A member of the array (randomNumbers[i]) is always, of course, going to be in the array. In fact $.inArray() when called to see if randomNumbers[i] is in the array will return i (if it's nowhere else, which in this case it can't be). Your loop won't get past the first number, so it'll just be 0.
I don't understand the point of your while loop. inArray only returns -1 if the value isn't found, which it will always be found, so you're just creating an infinite loop for yourself that will keep resetting the random number generated.
If you're just trying to add four random numbers to a div, this worked for me:
$(document).ready(function (e) {
var randomNumbers = new Array();
for (var i = 0; i < 4; i++) {
randomNumbers[i] = Math.floor((Math.random() * 9) + 1);
}
for (var i = 0; i < randomNumbers.length; i++) {
if ($('#output').html() !== '') {
var existingOutput = $('#output').html();
$('#output').html(existingOutput + randomNumbers[i]);
} else {
$('#output').html(randomNumbers[i]);
}
}
});
Further refactored:
$(document).ready(function (e) {
var randomNumbers = new Array();
for (var i = 0; i < 4; i++) {
randomNumbers[i] = Math.floor((Math.random() * 9) + 1);
}
for (var i = 0; i < randomNumbers.length; i++) {
$('#output').append(randomNumbers[i]);
}
});

Categories