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));
Related
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/
I want to write this function "guessPasscode", but don't think my codes work. (the other functions are correct) It is supposed to guess every number from 0000 ~ 9999 as four-digit passcodes.
I run the function and it doesn't print out anything, and I also don't think the function works the way I wanted it to.
var guess = "";
var guessCode ="";
function start() {
var secretPasscode = generateRandomPasscode();
guessPasscode(secretPasscode);
}
// Checks whether the given guess passcode is the correct passcode
function isCorrect(guessCode, correctCode) {
return guessCode == correctCode;
}
// Generates a random 4 digit passcode and returns it as a String
function generateRandomPasscode() {
var randomPasscode = "";
for(var i = 0; i < 4; i++) {
var randomDigit = Randomizer.nextInt(0, 9);
randomPasscode += randomDigit;
}
return randomPasscode;
}
function guessPasscode(secretPasscode){
for (var a = 0; a < 10; a++){
guess += a;
for (var b = 0; b < 10; b++){
guess += b;
for(var c = 0; c < 10; c++){
guess += c;
for (var d = 0; d < 10; d++){
guess += d;
if (isCorrect(guessCode, secretPasscode)){
println("Success!");
break;
}
guess = 0; //I am not sure about this line though
}
}
}
}
if (isCorrect(guessCode, secretPasscode)){
println("Success!");
}
}
I expect it to print "success" and stop the loop after it has found the correct password.
Those nested for loops are really wild and incredibly inefficient. If you want to guess from 0 to 9999, just run the loop through and then pad zeroes to the left.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
for (let i = 0; i < 9999; i++) {
let guess = String(i).padStart(4, '0')
guessAnswer(guess)
//whatever logic here to exit loop on correct guess
}
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);
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;
}
Trying to make a loop that outputs 2 to the power of 0-31. So far I only have it giving me 2 to the power of 31. What am I doing wrong?
function findPower()
{
var answer=0;
for(var i=0;i<=31;i++)
{
answer=Math.pow(2,i);
}
document.getElementById("output").innerHTML=answer;
}
Because in the loop in each iteration you are overriding the value of answer, so at the end it will have the value of last iteration only.
If you want to iterate the value of each number, then an easy solution is to push them to an array and after the loop join them to create the answer string as below
function findPower() {
var answer = [];
for (var i = 0; i <= 31; i++) {
answer.push(Math.pow(2, i));
}
document.getElementById("output").innerHTML = answer.join(', ');
}
function findPower() {
var answer = [];
for (var i = 0; i <= 31; i++) {
answer.push(Math.pow(2, i));
}
document.getElementById("output").innerHTML = answer.join(', ');
}
findPower();
<div id="output"></div>
You statement inside loop "document.getElementById("output").innerHTML=answer;" is overriding previous value so you are getting the last value. So what I did is to concatinate the values instead of overriding previous values
it should like following
function findPower() {
var answer = 0;
for (var i = 0; i <= 31; i++) {
answer = Math.pow(2, i);
document.getElementById("output").innerHTML = document.getElementById("output").innerHTML + "," + answer
}
}
<body onload="return findPower();">
</body>
<span id="output"></span>
If I get you right you want to calculate a sum of powers of 2:
for (var i = 0; i <= 31; i++) {
answer += Math.pow(2, i);
}
Notice the "+" sign. Writing:
answer += Math.pow(2, i);
Is the same as writing:
answer = answer + Math.pow(2, i);
Maybe it's better and faster.
function findPower() {
var answer = [];
var pow = 1;
answer.push(pow);
for (var i = 1; i <= 31; i++) {
pow *= 2;
answer.push(pow);
}
document.getElementById("output").innerHTML = answer.join(', ');
}