Factorial will not multiply - javascript

When I run the code it doesn't multiply my number it just outputs in a loop until it reaches 1
I have tried multiple different ways and this one is the closest i've gotten
......................................
var BR="<br />"; //html line break
function factorial(Num) {
document.write("The factorial of your number is" +Num +BR);
if (Num == 1 ) return 1;
else return (Num * factorial(Num-1));
}
.....................................................
.......................................
var Num; //users number
var Numfactorial;
var ES="";
var factorial
Num=prompt("Enter a number between 1-20" +ES);
Numfactorial=factorial(Num);
.........................................
It's supposed to take the number and multiply it down, so say you put in 20 it should go 19*18*17... down until it multiplies 1 and then outputs the product.

Place the document.write outside your function, and just print the result (Numfactorial) to the page. You also need to parse Num to a number, and remove var factorial:
var BR = "<br />";
function factorial(Num) {
if (Num == 1) return 1;
else return Num * factorial(Num - 1);
}
var Num;
var Numfactorial;
var ES = "";
Num = parseInt(prompt("Enter a number between 1-20" + ES));
Numfactorial = factorial(Num);
document.write("The factorial of your number is " + Numfactorial + BR);

Well, that is the expected output of your code. Your function factorial is returning your value which you aren't using to display the value. You should instead write it like this:
....................................................
var BR="<br />"; //html line break
function factorial(Num) {
if (Num == 1 ) return 1;
else return (Num * factorial(Num-1));
}
.....................................................
.......................................
var Num; //users number
var Numfactorial;
var ES="";
var factorial
Num=prompt("Enter a number between 1-20" +ES);
Numfactorial=factorial(Num);
document.write("The factorial of your number is" +Numfactorial +BR);
.........................................

Related

Javascript how to adding minus number and positive number

i made a simple program convert number to word. and i got problem when i want to convert minus number.
I want to find the index in the array 'satuan' so that later I add the word 'minus'
in my code i use Indonesian language btw.
js code:
// i have array like this
var satuan = ['', 'satu', 'dua', 'tiga', 'empat', 'lima', 'enam', 'tujuh', 'delapan', 'sembilan'];
// and my function to convert minus number like this
function convert_minesPuluhan(num) {
var c = Math.abs(num) + Math.abs(num);
if (num < 0 && num > -10) {
return satuan[num + c];
}
}
but when i console.log(num + c). the result is (example the num value is -1) -12.
but what I want is -1 + 1 + 1 = 1
// so i want like this
satuan[1];
how to solve this?
You are most likely getting a string for num
So, you'll have to do num = parseInt(num) first to convert it into an int datatype.
i.e.
function convert_minesPuluhan(num) {
num = parseInt(num)
var c = Math.abs(num) + Math.abs(num);
if (num < 0 && num > -10) {
return satuan[num + c];
}
}
Try this, your code is working fine. I understand that you need to add the 'minus' keyword before negative numbers.
var satuan = ['', 'satu', 'dua', 'tiga', 'empat', 'lima', 'enam', 'tujuh', 'delapan', 'sembilan'];
// and my function to convert minus number like this
function convert_minesPuluhan(num) {
var c = Math.abs(num) + Math.abs(num);
if (num < 0 && num > -10) {
console.log("minus " + satuan[num + c])
return "minus " + satuan[num + c];
}
}
convert_minesPuluhan(-5)
You need to convert the input of your function to integer
You are adding 2 strings in your function "-1" and "2" and thats why youre getting "-12" which is undefined.
let num = parseInt(num);
Try this inside your function and rest all is the same.

whats the problem with the custom power function I designed(javascript)?

The question which is suggested it is a question which is based on calculating fractional power of number but I wanted it simply in integer form.The function power is showing the powers correctly of a number raised to power b but it is not stopping as expected it should be.When I try to return the sum as return sum at the end of function power it is just loading and showing nothing please help me.Any help will be greatly appreciated.I cant use the built in pow() function.Thanks.
function power(a, b) {
a = parseInt(a);
b = parseInt(b);
var sum = 1;
var result;
var pow = 1;
for (var i = 1; i <= b; i++) {
pow = 1;
if (i == 1) {
pow = a * i;
sum = 1;
} else {
i--;
pow = a * i;
sum = sum * pow;
alert(sum);
}
}
}
var a = prompt("Enter the number a for calculating its power?");
var b = prompt("Enter the number for calculating pow of a i.e enter power of a");
var answer = power(a, b);
alert("a^b is equal to : " + answer);
If you are interested in recursive function call, check this out.,
var power = function(a, b)
{
a = parseInt(a);
b = parseInt(b);
if (b === 0)
{
return 1;
}
else
{
return a * power(a, b-1);
}
};
var a = prompt("Enter the number a for calculating its power?");
var b = prompt("Enter the number for calculating pow of a i.e enter power of a");
alert("the result "+ a + " ^ " + b + " is " + power(a, b));

How to sum numbers from 1 through user's entry, using while-loop, do-loop?

I am trying to complete the following code to achieve the sum of numbers from 1 to 100(user's entry must be 1-100), using whileloop or doloop. I am new to this so, any help is much appreciated!
In the following code, I used prompt method to get the user entry. Wrote the code, to sum numbers; from 1 through the user's entry. I displayed the result in an alert box. Now, my challenge is I want to display an error message if the user's entry outside the 1-100 range. And after that, I do not want to do any calculations if user clicks cancel and stop displaying the prompt box.
<!DOCTYPE html>
<html>
<head>
<title>Sum of Numbers</title>
<script>
var numbers = prompt("Enter a number 1-100");
while (numbers!=null && (isNaN(parseInt(numbers)) || parseInt(numbers) >100 || parseInt(numbers) <1)) {
numbers = prompt("Try again.Enter a number 1-100");
}
if (numbers !=null){
alert("Finally you entered a correct number");
}
var sum = 0;
var numOfLoops = numbers;
var counter = 1;
do {
sum+=counter;
counter++;
} while (counter<=numOfLoops)
alert ("sum=" +sum);
</script>
</head>
<body>
<script>
document.write("<h1>Sum of Numbers</h1>");
document.write("The sum of numbers from 1 to = " + numbers + " is = " +
+ sum + "<br><br>");
</script>
</body>
</html>
Simply move the calculation logic inside the condition where the user enters the correct input. This will make sure that the prompt closes automatically when you click on the cancel button (Prompt returns null when the user clicks on cancel)
<script>
var numbers = prompt("Enter a number 1-100");
while (numbers != null && (isNaN(parseInt(numbers)) || parseInt(numbers) > 100 || parseInt(numbers) < 1)) {
numbers = prompt("Try again.Enter a number 1-100");
}
if (numbers != null) {
alert("Finally you entered a correct number");
var sum = 0;
var numOfLoops = numbers;
var counter = 1;
do {
sum += counter;
counter++;
} while (counter <= numOfLoops)
alert("sum=" + sum);
}
</script>
You could simply use a do…while to solve your problem, e.g.:
let n = null;
do {
n = parseInt(prompt('Enter an int number between 1 and 100'));
} while (isNaN(n) || (n < 1 || n > 100));
let sum = n * (n + 1) / 2;
alert('The sum of all int numbers from 1 to ' + n + ' is: ' + sum);
N.B. The sum of the first n integer numbers can be computed as n * (n + 1) / 2, with O(1) complexity - reducing the O(n) complexity of your for loop.

while loop test case errors

The question as per the practice course is :
Write a JavaScript program to find the maximum integer n such that (1 + 2 + ... + n <= given integer ) is true. For eg. If a given integer is 10, value of maximum integer n is 4 so that 1+2+3+4 <= 10 is true. Your output code should be in the format console.log("Value of n is ", variableName)
My code is :
var num = prompt("Enter a number");
function test(x) {
var sum = 1,
n = 1,
a = 0;
while (sum <= x) {
sum += n;
n = n + 1;
a += 1;
}
return a;
}
var output = test(num);
console.log("Result is :", output);
I'm getting the correct outputs as per the test cases I've entered(10-4,15-5,16-6,17-6) but the website says there is something wrong with the program.
What am i doing wrong?
Better answer than looping: exploit maths. Starting with Triangular number formula:
1 + 2 + ... + n = n * (n + 1) / 2
Thus, for input x, you need to find n such that
n * (n + 1) / 2 <= x
To solve this, we need to clean up the inequality, then use the quadratic equation formula:
n^2 + n <= 2x
n^2 + n - 2x <= 0
n <= (-1 + sqrt(1 + 8x)) / 2
as the final solution. e.g. for
x = 10: n <= (-1 + sqrt(81)) / 2; n <= 4
x = 16: n <= (-1 + sqrt(128)) / 2; n <= 5.156854249492381
Round the upper limit down, and you have the largest allowed integer. Translated into JavaScript:
function test(x) {
return Math.floor((Math.sqrt(8 * x + 1) - 1) / 2);
}
var num = prompt("Enter a number");
console.log("Result is :", test(num));
Consider if the passed value is 11. Then, the maximum integer n should be 4, because 1+2+3+4 < 11 is true, while 1+2+3+4+5 < 11 is false. Your current code outputs 5 for an input of 11, though, which is incorrect; your while loop is sometimes overshooting sum.
You also need to initialize sum to start at 0, not at 1.
Subtract one from a before returning it:
function test(x) {
var sum = 0,
n = 1,
a = 0;
while (sum <= x) {
sum += n;
n = n + 1;
a += 1;
console.log(a, sum);
}
return a - 1;
}
console.log(test(10));
console.log(test(11));
var num = prompt("Enter a number");
var output = test(num);
console.log("Result is :", output);
The code below should work for you. Basically, what I did was that if the input is 10, and your sum is 9, it will still go into the while loop. Then it will add n again and now your number is greater than your input (which is 10), but you still return it. Here what I did is that at the end of the while loop, if your sum is greater than your input, subtract one from a. That way it will still execute, but it will fix the problem.
Also another error I noticed was that sum started at 1, and n started at 1. You wanted 1+2+3+...+n, however using your previous method, you got 1+1+2+3+...+n.
var num = prompt("Enter a number");
function test(x) {
var sum = 0,
n = 1,
tempSum = 1,
a = 0;
while (sum <= x) {
sum += n;
n++;
a++;
if (sum > x) {
a--;
}
}
return a;
}
var output = test(num);
console.log("Result is :", output);
Your order of operation is a little funky; all you have to do is add the incrementor. The while false case will make sure the sum only passes over the number once. So when you return, reduce the number by one:
var num = prompt("Enter a number");
var output = test(num);
console.log("Result is :", output);
function test(num){
let sum = 0
let inc = 0
while(sum<=num)
sum+=++inc
return --inc;
}
This is a reduced version of your code, basically we increment first the number to add (n) in each iteration, and then we add it to the variable holding the sum. When the loop conditions evaluates to false you need to decrement one to n to get your value:
var num = prompt("Enter a number");
function test(x)
{
var sum = 0, n = 0;
while (sum <= x)
{
sum += (++n);
}
return --n;
}
var output = test(num);
console.log("Result is :", output);
I think this will work for you:
var num = prompt("Enter a number");
function test(x) {
var sum = 1,
n = 0;
while ((sum+n) <= x) {
n = n + 1;
sum += n;
}
return n;
}
var output = test(num);
console.log("Result is :", output);
Try below function to find max Number
function maxNumber(a){
var i=1,sum=0,maxNumber=0;
while(sum<=a) {
sum=sum+i;
if(sum<=a)
{
maxNumber=i;
}
i+=1;
}
return maxNumber;
}
doubled checked condition sum<=a to preserve the previous loop value and if condition not satisfied that means current loop value is not useful so returned preserved value of previous loop
Output tested :
Below will help you get the job done.
var num = prompt("Enter a number");
function findMaxNumber(num){
var sum = 0;
var counter = 0;
while(sum < num){
if(sum + counter > num){
break; // Exit loop
}
sum = sum + counter;
counter++;
}
return --counter; // Loop will cause this to be 1 higher than the max int.
}
console.log('Result is: ' + findMaxNumber(num));

Average of input prompt numbers

I am having an issue with getting the average of the numbers that are inputted through a prompt window. I need to display the numbers like i have so far, but I can't seem to get them to add together to get the average.
here is my code so far.
<html>
<body>
<script type="text/javascript">
function show_prompt() {
i = 0;
do {
var number = prompt("Please Enter a Number");
var number = parseInt(number);
i++;
document.write("Number: " + number);
document.write("<br>");
}
while (i < 5);
}
show_prompt();
var avrg = number + number + number + number + number
document.write('Average of scores : ' + avrg);
</script>
</body>
</html>
You have to move calculation inside function. Also you can do it simplier:
function show_prompt() {
var i = 0;
var sum = 0;//declare a variable to keep the sum of numbers
do {
var number = prompt("Please Enter a Number");
sum += parseInt(number); //sum the numbers here
i++;
document.write("Number: " + number);
document.write("<br>");
}
while (i < 5);
document.write('Average of scores : ' + sum / i);//use the sum of the numbers divide by the the numbers the user enters
}
show_prompt();
Tried to comment your old code with the mistakes:
function show_prompt() {
i = 0;
do {
//there is no need to declare number twice
//also you don't sum somewhere the numbers you get from the user
var number = prompt("Please Enter a Number");
var number = parseInt(number);
i++;
document.write("Number: " + number);
document.write("<br>");
}
while (i < 5);
}
show_prompt();
//number is out of scope of function show_prompt so is undefined
var avrg = number + number + number + number + number
//to get an avg you have to divide the sum by the number
document.write('Average of scores : ' + avrg);
Notice your var number is scoped within show_prompt(), it is not visible outside of it.
You need to have your show_prompt function not loop, and return the number, and have another function that calls show_prompt multiple times, takes the returns and calculate the average.. Also, your code is just calculating the sum, not the average
I'm not going to show you the exact code, but here's the idea
calc_average:
var sum=0;
loop 5 times:
sum = sum + show_prompt();
average = sum/5;
show_prompt:
var number = prompt('blah blah');
return number

Categories