factorial of a number - javascript

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

Related

Is finding the factorial of 5000 possible in javascript

I want to find the factorial of 5000 but once I try to pass 100 it'll return infinity. Is there are way to bypass this and get the result? I am trying to get the time it takes to solve this.
function testSpeed(n) {
if (n > 0 && n <= 1) {
return 1;
} else {
return n * testSpeed(n-1);
}
}
console.log(testSpeed(5000));
As you've noticed, Javascript numbers can only get so big before they just become "Infinity". If you want to support bigger numbers, you'll have to use BigInt.
Examples:
// Without BigInt
console.log(100 ** 1000) // Infinity
// With BigInt
// (stackOverflow doesn't seem to print the result,
// unless I turn it into a string first)
console.log(String(100n ** 1000n)) // A really big number
So, for your specific bit of code, all you need to do is turn your numeric literals into BigInt literals, like this:
function testSpeed(n) {
if (n > 0n && n <= 1n) {
return 1n;
} else {
return n * testSpeed(n-1n);
}
}
console.log(String(testSpeed(5000n)));
You'll find that youe computer can run that piece of code in a snap.
This seems to give the correct result (according to https://coolconversion.com/math/factorial/What-is-the-factorial-of_5000_%3F)
const longFactorial = (num) => {
let result = num;
for (let i = 1n; i < num; i++) {
result = result * (num - i)
}
return String(result);
}
console.log(longFactorial(5000n));
I can receive for 170! maximum:
function factorial (y){
if (y ==0 || y ==1){
return 1;
}
else {
f = y - 1;
while (f >= 1) {
y = y * f;
f--;
}
return y;
}
}
console.log(factorial(170));

Get sum of sequence using recursion

I have this sum:
Obviously, I have to get sum of that depending on what N is. I need to do it in three different ways.
First is for loop:
function lab(n) {
var S = 0;
let VS
if (n == 0) {
VS = 0;
return 0;
}
if (n == 1) {
VS = 4;
return Math.pow(3 / 5, 1);
} else {
for (let i = 0; i < n; i++) { //
S += 1 / n * Math.pow(3 / 5, n);
t = 4 * n;
}
return S;
}
}
Second one is recursion:
function lab(n) {
let vs = 0;
if (n <= 1)
return 0;
else {
vs += 4 * n // vs is how many actions it takes to make this calculation. I’m sure in for loop this is right, but I’m not sure about the recursion approach
return lab(n - 1) + 1 / n * Math.pow(3 / 5, n)
}
}
The third way is use recursion with the condition that in order to get S(n) I need to use S(n-1).
I am stuck on this.
Also I get different sums with the same Ns from first and second function.
I am not sure what you are asking for.
If you are asking for a recursive function then take a look at the following:
function summation(n, sum = 0) {
if (n <= 0) {
return sum;
}
sum += (1/n) * Math.pow(3/5, n);
return summation(n - 1, sum);
}
console.log(summation(1));
console.log(summation(2));
console.log(summation(3));
console.log(summation(4));
console.log(summation(5));
Another recursive method without passing sum as parameter:
function summation(n) {
if (n <= 0) {
return 0;
}
return ((1/n) * Math.pow(3/5, n)) + summation(n - 1);
}
console.log(summation(1));
console.log(summation(2));
console.log(summation(3));
console.log(summation(4));
console.log(summation(5));
Also, for the loop method, the following will suffice
function summation(n) {
var sum = 0;
while (n > 0) {
sum += (1/n) * Math.pow(3/5, n);
n -= 1;
}
return sum;
}
console.log(summation(1));
console.log(summation(2));
console.log(summation(3));
console.log(summation(4));
console.log(summation(5));

Prime Check JavaScript

What have I done wrong with this code? It can't print anything on the console.
Here it is the description of the problem:
Implement a javascript function that accepts an array containing an integer N and uses an expression to check if given N is prime (i.e. it is divisible without remainder only to itself and 1).
var n = ['2'];
function isPrime(n) {
if (n < 2) {
return false;
}
var isPrime = true;
for(var i = 2; i < Math.sqrt(n); i += 1) {
if (n % i === 0) {
isPrime = false;
}
}
return isPrime;
}
return isPrime(n);
There are couple errors in your code.
First, you need to check for every integer between 2 and Math.sqrt(n) inclusively. Your current code returns true for 4.
I don't think this is in a function, so you need to omit return from return isPrime(n) and replace it with a function wich prints out the return value of the funnction, like alert or console.log.
n is not a number, it's an array. You need to either make n a number, or call the function with isPrime(n[0]).
The correct code is
var n = 2;
function isPrime(n) {
if (n < 2) {
return false;
}
var isPrime = true;
for(var i = 2; i <= Math.sqrt(n); i += 1) {
if (n % i === 0) {
isPrime = false;
}
}
return isPrime;
}
alert(isPrime(n));
Note: You can change n += 1 to n++, and it works the same way.
n is an array, you want to access first element in the array and convert it to number first.
try replacing
return isPrime(n);
with
return isPrime(parseInt(n[0],10));
Your for-loop condition also needs a little modification
for(var i = 2; i <= Math.sqrt(n); i += 1) { //observe that i is not <= Math.sqrt(n)
A couple of little errors:
var n = 2;//<--no need to put n in an array
function isPrime(n) {
if (n < 2) {
return false;
}
var isPrime = true;
for(var i = 2; i < Math.sqrt(n); i += 1) {
if (n % i === 0) {
isPrime = false;
}
}
return isPrime;
}
isPrime(n);//<--no need for "return"
As to no output being printed, it is because you need to use console.log.
Replace return isPrime(n); with console.log(isPrime(n));.
Full working code:
var n = ['2', '3', '4', '5', '6', '7']; // you can use as many values as you want
function isPrime(n) {
if (n < 2) {
return false;
}
var isPrime = true;
for (var i = 2; i <= Math.sqrt(n); i += 1) { // Thanks to gurvinder372's comment
if (n % i === 0) {
isPrime = false;
}
}
return isPrime;
}
n.forEach(function(value) { // this is so you can iterate your array with js
console.log('is ' + value + ' prime or not? ' + isPrime(value)); // this so you can print a message in the console
});
/*
// Another approach of parsing the data, uncomment this piece of code and comment the one above to see it in action (both will give the same result)
for (index = 0; index < n.length; ++index) {
console.log('is ' + n[index] + ' prime or not? ' + isPrime(n[index])); // this so you can print a message in the console
}
*/

Factorialize a Number

I'm taking the freecodecamp course one of the exercises it's to create a Factorialize function, I know there is several ways to do it just not sure what this one keeps returning 5
function factorialize(num) {
var myMax = num;
var myCounter = 1;
var myTotal = 0;
for (i = 0; i>= myMax; i++) {
num = myCounter * (myCounter + 1);
myCounter++;
}
return num;
}
factorialize(5);
This is a recursive solution of your problem:
function factorialize(num) {
if(num <= 1) {
return num
} else {
return num * factorialize(num-1)
}
}
factorialize(5)
This is the iterative solution:
function factorialize(num) {
var cnt = 1;
for (var i = 1; i <= num ; i++) {
cnt *= i;
}
return cnt;
}
factorialize(5)
with argument 5, it will return the 5! or 120.
To answer your question, why your function is returning 5:
Your function never reaches the inner part of the for-loop because your testing if i is greater than myMax instead of less than.
So you are just returning your input parameter which is five.
But the loop does not calculate the factorial of num, it only multiplies (num+1) with (num+2);
My solution in compliance with convention for empty product
function factorializer(int) {
if (int <= 1) {
return 1;
} else {
return int * factorializer(int - 1);
}
}
Here is another way to solve this challenge and I know it is neither the shortest nor the easiest but it is still a valid way.
function factorialiaze(num){
var myArr = []; //declaring an array.
if(num === 0 || num === 1){
return 1;
}
if (num < 0){ //for negative numbers.
return "N/A";
}
for (var i = 1; i <= num; i++){ // creating an array.
myArr.push(i);
}
// Reducing myArr to a single value via .reduce:
num = myArr.reduce(function(a,b){
return a * b;
});
return num;
}
factorialiaze(5);
Maybe you consider another approach.
This solution features a very short - cut to show what is possible to get with an recursive style and a implicit type conversion:
function f(n) { return +!~-n || n * f(n - 1); }
+ convert to number
! not
~ not bitwise
- negative
function f(n) { return +!~-n || n * f(n - 1); }
var i;
for (i = 1; i < 20; i++) {
console.log(f(i));
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
Try this function
const factorialize = (num) => num === 0 ? 1 : num * factorialize(num-1)
Use it like this:
factorialize(5) // returns 120
Try this :
function factorialize(num) {
var value = 1;
if(num === 1 || num ===0) {
return value;
} else {
for(var i = 1; i<num; i++) {
value *= i;
}
return num * value;
}
}
factorialize(5);
// My solution
const factorialize = num => {
let newNum = 1;
for (let i = 1; i <= num; i++) {
newNum *= i
}
return newNum;
}
I love syntactic sugar, so
let factorialize = num => num <= 1 ? num : num * factorialize(num -1)
factorialize(5)

Javascript Happy Numbers not working

Here I have a function that should take a number n into the disHappy(n) to check if all
n in [n-0) are happy.
Happy Numbers wikipedia
If I only run happyChecker(n), I can tell that 7 is happy, but disHappy(n) doesn't show it. It is as if it doesn't receive the true. I have used console.log()'s all over the place and happyChecker(n) shows a number that SHOULD return true. When I placed a console.log() above the return true; for if(newNum===1), it showed that it branched into that branch but it just didn't seem to return the true.
function happyChecker(n) {
var arr = [];
var newNum = 0;
//here I split a number into a string then into an array of strings//
num = n.toString().split("");
for (var i = 0; i < num.length; i++) {
arr[i] = parseInt(num[i], 10);
}
//here I square each number then add it to newNum//
for (var i = 0; i < arr.length; i++) {
newNum += Math.pow(arr[i], 2);
}
//here I noticed that all unhappy numbers eventually came into one of these three//
//( and more) numbers, so I chose them to shorten the checking. A temporary solution for sure//
if (newNum === 58 || newNum === 4 || newNum == 37) {
return false;
}
if (newNum === 1) {
return true;
} else {
happyChecker(newNum);
}
}
function disHappy(num) {
for (j = num; j > 0; j--) {
if (happyChecker(j)) {
console.log(j + " is a Happy Number. It's so happy!!!.");
}
}
}
When you recurse, you need to return the value returned:
if (newNum === 1) {
return true;
} else {
return happyChecker(newNum);
}
You also should declare "num" with var.
I'm ordinarily not a "code golfer", but this is a good example of how the (new-ish) iterator utility methods on the Array prototype can clean up code. You can use the .reduce() function to traverse the array of digit characters and do the work of squaring and summing all at once:
var newNum = n.toString()
.split('')
.reduce(function(sum, digit) {
return sum + (+digit * +digit);
}, 0);
The call to .toString() returns a string, then .split('') gives you an array. Then .reduce() starts with an initial sum of 0 and for each element of the array (each digit), it adds to it the square of that digit. (Instead of parseInt() I just used the + unary operator; we know for sure that each string will be a valid number and an integer.)
You need to add return to the happyChecker call.
return happyChecker(newNum);
see:
http://jsfiddle.net/YjgL8/2/
here is my implementation
var getSum = function (n) {
if (!n >= 0) return -1;
var digits = n.toString().split("");
var sum = 0;
for (var i = 0; i < digits.length; i++) {
var digit = parseInt(digits[i], 10);
sum += digit * digit;
}
return sum;
}
/**
* #param {number} n
* #return {boolean}
*/
var isHappy = function(n, visited) {
if (n < 0) return false;
if (n === 1) return true;
if (typeof visited === 'undefined') visited = {};
sum = getSum(n);
if (visited[sum]) return false; // cycle
visited[sum] = true;
return isHappy(sum, visited);
};
Complete Example of finding happy numbers in range of custom number.
function happyNumbers() {
var result = document.getElementById("happy-result")
var inputy = parseInt(document.getElementById("happyValue").value)
result.innerHTML=""
for (i = 1; i < inputy; i++) {
(happy(i, i))
}
}
function happy(value,value2) {
var result = document.getElementById("happy-result")
var lengthNum = value.toString().length;
var resultNumbers = 0
for (var b = 0 ; b < lengthNum; b++) {
resultNumbers = resultNumbers + parseInt(value.toString().charAt(b)) * parseInt(value.toString().charAt(b))
}
if (resultNumbers == 4) {
return false
} else if (resultNumbers == 1) {
result.innerHTML += "<br> happy number " + i
return true
}else{
happy(resultNumbers, value2);
}
}
window.onload=happyNumbers()
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="panel panel-default">
<div class="panel-heading">happy numbers</div>
<div class="panel-body">
<label>Enter the number that you want ot have see happy numbers uo to it</label>
<input id="happyValue" oninput="happyNumbers()" value="100" class="form-control" />
<div id="happy-result"></div>
</div>
</div>

Categories

Resources