For the following functions that use addition assignment, the value of ans is always changed to 1 when an integer greater than 1 is passed
let ans = 0;
function reduce(num){
if(num == 0){
return 0;
}
ans += reduce(num-1);
return 1;
}
reduce(5);
console.log(ans); // 1
But when I save the recursive result to another variable first, the function works fine (ans will be changed to num-1)
let ans = 0;
function reduce(num){
if(num == 0){
return 0;
}
let tmp=reduce(num-1);
ans += tmp;
return 1;
}
reduce(5);
console.log(ans); // 4
How does this happen? Is this a feature of Javascript or a bug in the environment?
I have tried similar C codes and they all behave the same
#include<stdio.h>
int reduce(int num);
int ans;
int main(){
ans = 0;
reduce(5);
printf("%d",ans); // 4
}
int reduce(int num){
if(num == 0){
return 0;
}
int tmp=reduce(num-1);
ans += tmp;
// ans += reduce(num-1);
return 1;
}
Environment:
Microsoft Edge 97.0.1072.55
JavaScript V8 9.7.106.18
This happens because in JavaScript ans += reduce(num-1) is evaluated as:
ans = ans + reduce(num-1)
and not as:
ans = reduce(num-1) + ans;
(See (13.15.2) Runtime semantics: evaluation in the ECMAScript specs).
So ans is evaluated before the recursive call is made, and it is that evaluated value that is used as the operand of the addition.
You can avoid such unexpected behaviour by avoiding functions with side-effects. A pure recursive solution would be:
function reduce(num) {
if (num < 2) {
return 0;
}
return reduce(num-1) + 1;
}
let ans = reduce(5);
console.log(ans); // 4
numbers = [];
for (x = 1; x <= 1e4; x++) {
numbers.push(x)
}
//console.log(numbers)
function checkPrime(num) {
if (num == 1 || num == 0) {
return 'It is a separate case'
}
if (num == 2) {
return num + ' is prime'
}
for (var i = 2; i < num; i++) {
if (num in numbers) {
if (num % i === 0) return num + ' is not prime';
else {
return num + ' is prime';
}
return num !== 1;
} else {
return num + ' is not in range';
}
}
}
console.log(checkPrime(27));
Hi.
In the above code, I tried to create a function which returns information about whether a number is prime or not.
However, it fails in some cases. Like eg. in the case of 27 or 145, it returns the values are prime, which obviously is false. How can I amend this program to make it work?
Also, what is the smartest way of merging the case for number 2 and the rest prime numbers?
Thanks in advance and sorry if this is too basic, I could not find the right answer anywhere else.
You are putting the 'else' clause that states the number is prime before having finished to check all numbers until itself -1.
To be optimal, you don't need to loop until the number ( < num). Just until the square root of the number. (even better than looping until num/2) For example : 167 can be seen that is prime when the loop has reached 13. 13*13 = 169 > 167 so you can stop and safely afirm that 167 is prime.
For number 2 it is correct to have a sepparate case.
Below is the code for checking a single value if it is prime:
function checkPrime(num) {
if (num == 1 || num === 0) {
return 'It is a separate case'
}
if (num == 2) {
return num + ' is prime'
}
for (var i = 2; i < Math.sqrt(num); i++) {
if (num % i === 0) return num + ' is not prime';
}
return num + ' is prime';
}
alert(checkPrime(27));
I have rewritten the code to provide the right answer
numbers = [];
for (x = 1; x <= 1e4; x++) {
numbers.push(x)
}
//console.log(numbers)
function checkPrime(num) {
if (num == 1 || num == 0) {
return 'It is a separate case'
}
// check this condition outside the loop
if (!(num in numbers)) {
return num + ' is not in range';
}
if (num == 2) {
return num + ' is prime'
}
for (var i = 2; i < num; i++) {
if (num % i === 0) {
return num + ' is not prime';
}
}
return num + ' is prime';
}
console.log(checkPrime(27));
I've rewritten your code and made a couple of changes.
The reason you were having your problem is that you were returning in the for loop meaning all odd numbers would declare themselves as prime numbers.
I've fixed this but also I've I rearranged things a little, to be as efficient as possible it's good to bail as soon as possible so I do a couple of checks to bail initially I check if the number is in range, if not bail.
I've commented the code so it makes sense but if you don't understand why I've done something feel free to ask.
// make an array of all numbers between 0 and 10000
numbers = [];
for (x = 0; x <= 1e4; x++) {
numbers.push(x)
}
function checkPrime(num) {
// return if input number is not in numbers array
if (numbers.indexOf(num) == -1) return num + ' is not in range'
// return if number is 0 or 1
if (num <= 1) return 'It is a separate case'
// check all numbers between 2 and input number
// return if any number devides neatly
for (var i = 2; i < num; i++)
if (num % i === 0) return num + ' is not prime';
// if you get this far it's prime
return num + ' is prime';
}
console.log(checkPrime(27));
Personally, for the range, I wouldn't have an array of all the values but I've left this in just in case there was some other reasoning we don't know about.
EDIT:
As you've said the initial array is not important I've remade the code to work without it, I've not included comments this time (to save space) but that code does the same thing and is mostly unchanged.
function checkPrime(num) {
if (num < 0 || num > 1e4) return num + ' is not in range'
if (num <= 1) return 'It is a separate case'
for (var i = 2; i < num; i++)
if (num % i === 0) return num + ' is not prime';
return num + ' is prime';
}
console.log(checkPrime(27));
Anyway, I hope you find this helpful 🙂
I'm trying to create a script that returns the factorial of the input number as part of a challenge. When I try to run it, it returns the proper factorial, but apparently I did it wrong somehow.
It looks like this:
function FirstFactorial(num) {
if (num > 1) {
var x = num;
for (var i = 1; i < x; i++) {
num = num * i;
}
} else if (num === 1) {
return 1;
} else {
console.log("That's not a number!");
}
return num;
}
Then I tried doing it like this, but it still doesn't work!
function FirstFactorial(num) {
if (num < 0) {
num = 0;
console.log("You have to input a number!");
}
if (num === 0) {
return 1;
}
return num * FirstFactorial(num - 1);
}
The most likely reason is that they expected and intended you to use recursion (a function that calls itself).
If you think about factorials, each builds on the result of the previous one, which is the classic case for using recursion.
(Note that I'm specifically not posting code doing this with recursion, because presumably the point here is for you to work out how to do it.)
I'm new to javascript and I'm having a hard time figuring out how to get this factorial function to work. Here's my code now.
var x = prompt("Enter a number"); {
function fact(x) {
if (x < 0) {
return ("Enter a positive integer");
}
else {
return (x * fact(x-1))
}
}
}
var result = fact(x)
document.write("The factorial of" + x + "is" + result);
Thanks for the help!
your base case is wrong for a recursive factorial. change it to
function fact(x) {
if (x <= 1) {
return 1
}
else {
return (x * fact(x-1))
}
}
Your definition of factorial is wrong. The traditional recursive definition of factorial is:
F(x) => x == 1 ? 1 : x * F(x-1)
Or you can use the iterative definition
F(x) => var i = 1; for (j = 1..x) i = i * j
In javascript, the recursive version would be:
function factorial (x) {
if (x == 1) return x;
return x * factorial(x-1);
}
The iterative version would be:
function factorial (x) {
var result = 1;
for (var y = 1; y <= x; y++) {
result = result * y;
}
return result;
}
You can add the negative number check in the above functions. But in my opinion that would obscure the purpose of the function (which is to implement the traditional definition of factorial). A better approach is to move the negative number if() check outside of the factorial function. The if (x < 0) check has its own purpose that is separate from calculating factorials: input validation.
In every recursive function, there exists a stopping condition (in your case its if(x<=1)) without which, the function would go to infinite recursion. You had not added that stopping condition. Following is the working updated program:
var x = prompt("Enter a number"); {
function fact(x) {
if (x < 0) {
return ("Enter a positive integer");
}
else if(x <=1){
return 1;
}
else {
return (x * fact(x-1))
}
}
}
var result = fact(x)
document.write("The factorial of " + x + " is " + result);
In addition to fixing the flawed algorithm, I recommend moving your prompt into its own function for separation of concerns.
I also like the idea of using a while statement for this as well as doing a parseInt on the input:
function fact(x) {
while (x > 1) {
return (x * fact(x-1));
}
return x;
}
function doFact() {
var x = parseInt(prompt("Enter a positive integer"));
if (x < 1) {
doFact();
} else {
var result = fact(x);
alert("The factorial of " + x + " is " + result);
}
}
doFact();
I have the following code but it is not giving perfect result for factorial can u find it out plz
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title> New Document </title>
<script type="text/javascript">
function fact(num)
{
var x=parseInt(num);
//alert(x+1);
if(x>0)
x=x* fact(x-1);
alert(x);
}
</script>
</head>
<body>
<form name="f1">
Enter the Number :<input type="text" length="8" name="txt1"><br>
<input type="button" value="Find factiorial" onclick="fact(txt1.value)">
</form>
</body>
</html>
You have to return the value. Here you go:
function fact(x) {
if(x==0) {
return 1;
}
return x * fact(x-1);
}
function run(number) {
alert(fact(parseInt(number, 10)));
}
and
<input type="button" value="Find factiorial" onclick="run(txt1.value)">
(How to make it work for negative numbers I leave up to you ;) (but I showed in this post anyway))
Just for fun, a more correct, non recursive algorithm:
function fact(x) {
if(x == 0) {
return 1;
}
if(x < 0 ) {
return undefined;
}
for(var i = x; --i; ) {
x *= i;
}
return x;
}
Use loop its easy to implement
function fact(num)
{
if(num<0)
return "Undefined";
var fact=1;
for(var i=num;i>1;i--)
fact*=i;
return fact;
}
<input type="button" value="Find factiorial" onclick="alert(fact(6))">
function factorial(n) {
return (n != 1) ? n * factorial(n - 1) : 1;
}
alert( factorial(5) );
You can try to use recursion method
Your function doesn't return anything, ever.
What do you do when x is 0?
Minor point - apart from alert, you don't really do anything with the returned value.
Try this instead, if you will (hover over the text):
if(x==0) return 1;
return x * fact(x-1);
Working example: http://jsbin.com/apuka3/2
You need to have a return in your function in the first place. ;)
I wrote this and it works.
var d = 1;
for (num; num > 1; num--) {
d *= num;
}
return d;
Here's a short recursive version:
function doFact(n) {
return +!(+(n)) || doFact(n - 1) * n;
}
function factorialFromInput() {
var theInputVal = document.getElementsByTagName("input")[0].value;
var theContainer = document.getElementById("resultContainer");
theContainer.innerHTML = "" + doFact(Math.abs(theInputVal));
}
.wrapper>* {
line-height: 2em;
width: 30%;
}
#resultContainer {
border: outset grey;
min-height: 1.1em;
padding-left: 0.3em;
background-color: #eff0f1;
overflow: scroll;
}
<div class="wrapper">
<input type="text" id="valEntered">
<br>
<button onclick="factorialFromInput();">Calculate Factorial</button>
<br>
<div id="resultContainer"></div>
</div>
function fact(n) {
if (n > 1) {
return n * fact(n-1);
} else {
return 1;
}
}
console.log(fact(5));
Using ternary operator we replace the above code in a single line of code as below
function fact(n) {
return (n != 1) ? n * fact(n - 1) : 1;
}
console.log(fact(5));
This is the very easiest way and latest JS(ES6)
factorial = n => n - 1 > 0 ? n * factorial(n - 1) : n;
//output
console.log(factorial(5));
Here I used ES6 arrow function. For better understanding please see what is arrow function.
Recursion in JS is open to stack overflow error and also very slow. Looping by other means is better. My contribution to factorial code would be a straightforward one;
var fact = n => n > 0 ? Array.from({length: n}, (_,i) => i+1)
.reduce((p,c) => p*c)
: 1;
console.log(fact(5));
The important part of the function is this line:
x = x * fact(x-1);
but the fact function does not return a value, so this is the same as x * undefined. Try adding return x; to the bottom of your function.
1) When X=0 function should return 1;
2) Added return;
function fact(num)
{
var x=parseInt(num);
//alert(x+1);
if(x>0)
x=x* fact(x-1);
else
x=1;
return x;
}
usage
<input type="button" value="Find factiorial" onclick="alert(run(fact.value));">
A slight edit to Anton's code:
function fact(x) {
if(x>0)
return x* fact(x-1);
if(x===0)
return 1;
return null;
}
(factorial of a negative doesn't exist, but factorial of 0 is equal to 1, in this case, if a number is smaller than 0, the function will return null)
What about:
function fact(n) {
n = Math.round(n);
if (n < 2) {
return 1;
}
else {
return n * fact(n - 1);
}
}
?
My suggestion:
function fact(x) {
if (x<0) {
return Infinity
};
var _= 1
for ($=1;$<=x;++$) {
_*=$
};
return _
};
It simply returns the factorial of whatever "x" is.
Here is one I made using a while loop:
function factorialize(num)
{
i = 1;
b = 1;
while (i < num) {
b = b + (b * i);
i = i + 1;
}
return b;
}
<script src="jquery-3.1.0.js"></script>
<script>
$(function () {
var target = 5;
var factorial = 1;
for (var i = 1; i <= target; i++) {
factorial *= i;
}
alert(factorial);
});
</script>
you can set any value in target and this logic will calculate Factorial.
Thanks... :)
I am not sure why no one used dynamic programming to answer this, it's by far the most efficient way to build something on a factorial in my view.
var mem = [];
function fact(num)
{
var x = parseInt(num);
if (x == 0 || x == 1) return 1;
mem[x] = x * fact(x-1);
return mem[x];
}
a very simple form:
function fact() {
var x = document.getElementById("txtf").value;
var f=1;
for (var i=1; i <= x ; i++){
f = f*i;
}
document.getElementById('showR').innerHTML= f;
}
<input type="text" id="txtf" value="3">
<input type="button" id="btnf" value="click for calculate" onclick="fact()">
<p id="showR">/Factoriel/</p>
function factorial(num) {
var result = 1;
for (var i = 1; i <= num; i++) {
result = result * i;
}
return result;
}
//call function e.g factorial(4).. 1*2*3*4 it will evaluate in ascending order
var factorialNumber , factorial=1;
factorialNumber=prompt("Factorial Number" , "write Factorial Number");
for(var i = 1; i<= factorialNumber;i++){
factorial *= i;
}
alert(factorial);
The code above first defines two variables, factorialNumber and factorial. factorial is initialized with 1. factorialNumber will get the result of the prompt (a number is expected) and then, using a cycle, in each step, factorial is multiplied with the index of the step, which is represented by i. When successfully calculated, we show the result using alert.
With a Do loop, it is pretty easy.
<table>
<tr>
<th>Amount of integers</th>
<th>Answer</th>
</tr>
<tr>
<th><input id="int" type="number"/></th>
<th><input id="answer" type="number"/></th>
</tr>
</table>
<button onclick="calculate()">calculate</button>
<script>
function calculate() {
var input = document.getElementById("int").value;
var int = 1;
do {
var product = int *= input;
input--;
} while (input > 0);
answer.value = product;
}
</script>
You first set a table to act as a way to input your variable and have a place to output the answer. You also add a button to execute your function.
The input variable is the value entered by the user. You also have int variable as a placeholder.
Inside the do loop you then another variable that is the product, it takes your placeholder variable and times it by the input. After this the input decrements, as long as input value is then greater than zero the loop keeps iterating.
Then at the end, it posts the answer to the 'answer' id tag in the table.
function factorial (n) {
if (n > 1) {
return n * factorial(n-1);
}
return 1;
}
console.log("recursive way => ",factorial(5));
function factorial(num){
if(num<1||typeof num!=='number'){
return undefined
}
if(num===1){
return num
}
return num*factorial(num-1)
}
console.log(factorial(3))
https://jsfiddle.net/mohittadhiyal/6w64x0sL/10/
I've seen a recursive approach used in many places (Eloquent JavaScript etc). Here, the function is called recursively until it reaches 0, which should not be the case. We should only call the function till it is >= 2 because the last number we need to multiply by is 1.
It's a very minor change, and probably does not matter. Curious to know what other people think of it. Assuming it is a valid positive integer.
/**
* Popular approach - the recursive function is called till x is 0
*
* #param x
*/
function popularFactorial(x) {
console.log(x)
if(x === 0) {
return 1
} else {
return x * popularFactorial(x - 1)
}
}
var result = popularFactorial(8)
console.log(result)
/**
* Using this approach, the recursive function is called one less time
* i.e till x is 1
*
* #param x
*/
function factorial(x) {
console.log(x)
if(x === 0) {
return 1
} else if(x >= 2) {
return x * factorial(x - 1)
}
return x
}
var result = factorial(8)
console.log(result)
function factorial(n) {
return [...Array(n + 1).keys()].slice(1).reduce((total, currentValue) => total * currentValue, 1);
}
//This is fastest way to implement factorial
const fact = n => !n ? 1 : n * fact(--n);
console.log(fact(10))
i am quite new to javascript and would be happy to know any improvements that could be made to this answer
var a = 1;
function factorial(num) {
if (num == 0) {
return 1;
} else if (num < 0) {
return undefined;
} else {
for(i = num; i > 0; i--){
a *= i;
}
return a;
}
}
var b = factorial(5);
console.log(b);