Determining factorial of a number - javascript

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

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

infinite while loop in javascript

My problem question as in the practice course goes as follows:
Write a JavaScript program to create a function which takes 2 integers as inputs. The function divides the first integer with second integer as long as the result (Quotient) is an integer (i.e. remainder is zero) and return the quotient as result. Your output code should be in the format console.log("Result is ", variableName)
And below is my code:
var num = prompt("Enter number to divide");
var d = prompt("Enter divisor");
function divide(x, y) {
var result;
if (d === 1) {
result = num;
} else {
while (num % d === 0) { //while error
result = num / d;
}
}
return result;
}
var output = divide(num, d);
console.log("Result is: ", output);
If I remove the while loop, program works fine but the problem description says I have to use it.
What am I doing wrong?
There are a few issues:
1) If your function receives the arguments x and y, then use those inside his scope, don't access the global variables.
2) You are never changing the variables that are evaluated on the while condition, so the evaluation will be the same, ever!
3) Another good thing you can do is add some validation on the received arguments.
Now, your code, can be rearranged to this one:
function divide(x, y)
{
if (isNaN(x) || isNaN(y))
return "Invalid arguments!";
if (y === 1)
return x;
while (x % y === 0)
{
x = x / y;
}
return x;
}
var num = prompt("Enter number to divide");
var d = prompt("Enter divisor");
var output = divide(num, d);
console.log("Result is: ", output);
Your while loop is depending of num, but you donĀ“t assign a new value to it after a cycle. This lead to that the condition stays always the same.
var num = prompt("Enter number to divide");
var d = prompt("Enter divisor");
function divide(x, y) {
var result = x;
if (y === 1) {
return result;
} else {
while (result % y === 0) {
result = result / y;
}
}
return result;
}
var output = divide(num, d);
console.log("Result is: ", output);

Check for perfect number and print out divisors?

My goal is to create a program that checks whether the user input is a perfect number or not. It has validation for the numbers entered. If the input IS a perfect number, I'd like to print out each of the divisors. I tried using this method:
{
for(int number=2; number <= 10000 ; number++)
perfect(number);
return 0;
}
void perfect(int number)
{
int total = 0;
for (int i = 1; i < number; i++)
{
if (number % i == 0)
total += i;
}
if (number == total)
{
for (int x = 1; x < number; x++)
{
if (number % x == 0)
cout << x << " + ";
}
cout << " = " << number << endl;
}
}
However, I was unable to get the desired effect. I am very new to javascript and am struggling with inserting code in the correct way. Does anyone have a suggestion for how I can get the desired effect? Here is the code I have already written:
function check_prime() {
var input = document.getElementById("enteredNumber").value;
var number = parseInt(input);
if (isNaN(number)) {
alert("Oops! Please enter a valid number.");
document.getElementById("enteredNumber").value="";
document.getElementById("result").innerHTML = "";
document.getElementById("enteredNumber").focus();
}
else if (input.length === 0) {
alert("Please enter a number.");
document.getElementById("enteredNumber").focus();
}
else if (!isNaN(number)) {
if (is_perfect(number)) {
document.getElementById("answer").innerHTML = "Congratulations! " + number + " is a perfect number." ;
}
else {
document.getElementById("answer").innerHTML = "I'm sorry. " + number + " is not a perfect number. Try Again.";
}
}
else {
document.getElementById("answer").innerHTML = "Please enter a number.";
}
}
function is_perfect(number)
{
var temp = 0;
for(var i=1;i<=number/2;i++)
{
if(number%i === 0)
{
temp += i;
}
}
if(temp === number)
{
return true;
}
else
{
return false;
}
}
function clear_textbox(){
document.getElementById("answer").innerHTML = "";
document.getElementById("enteredNumber").value="";
document.getElementById("enteredNumber").focus();
}
I'd suggest revising your is_perfect() function to return an array of divisors if the number is perfect and null if the number is not perfect. Then the calling code has the divisors available for display when the input is a perfect number.
function is_perfect(number) {
var temp = 0;
var divisors = [];
for(var i=1;i<=number/2;i++) {
if (number%i === 0) {
divisors.push(i);
temp += i;
}
}
return temp === number ? divisors : null;
}
Then:
var divisors = is_perfect(number);
if (divisors) {
document.getElementById("answer").innerHTML = "Congratulations! " + number + " is a perfect number.";
// display the divisors somewhere; the alert is just for show
alert("Divisors: " + divisors.toString());
} else {
...
}
[Note: In an earlier version of this answer, I had initialized temp to 1 and divisors to [1] and had started the loop at 2, on the theory that 1 is always a divisor. Unfortunately, that's wrong, since 1 is not a proper divisor of 1. The revised version of is_perfect() now returns null for an argument of 1 instead of [1]. An alternative fix would have been to test explicitly for the case number === 1, but that's uglier (if perhaps a tiny bit more efficient, since it avoids one % evaluation).]
so I use 2^(n-1)*(2^n -1) formula (to generate a perfect number) and checking if last digit is 6 or 8 to check if x is perfect number.
Note: It's not perfect 100%
function pn(x) {
x = '' + x
for (var i = 0; i < Infinity; i++) {
perfnumgen = Math.pow(2, i - 1) * (Math.pow(2, i) - 1)
if (x === "" + perfnumgen && (perfnumgen % 10 === 8 || perfnumgen % 10 === 6))
return true
else if (perfnumgen > x)
return false
console.log("" + perfnumgen)
}
}

Calculates and outputs the factorial of variable n (n already initialized).

Here inbelow is the code. Could anybody tell that what's wrong with the code? The purpose is to the factorial result of var n. (suppose it's already declared)
for(var i = 0; i < 5; i++)
{
var n1 = Math.floor(rc4Rand.getRandomNumber() * 7) + 3;
document.write("The factorial of " + n1 + " is ");
outputFactorial(n1);
}
function outputFactorial(n)
{
//I have to add some context here to post this question.
if (n1 == 0) {
return 1;
}
else {
return (n1 * factorial(n1 - 1));
}
}
document.write(n);
Simple mistake: the name of the argument in your outputFactorial() function is n, but you're using n1 throughout the function, and thus entering an infinite recursion loop (if n1 != 0).
The factorial function must be change to outputFactorial
The n1 variables needs to be changed to n in the outputFactorial function
You have to do is Document.write(outputFactorial(n1));
Remove the outside of function Document.write

Division in javascript

function subtraction(num1, num2){
var num3;
num3 = num1 - num2;
document.writeln("Difference "+ num3);
return (num3);
}
function division(num1, num2){
difference = parseFloat(subtraction());
var x;
while(difference > 0){
difference = num1-num2;
x = x + 1;
}
document.writeln("Quotient" + x);
}
Hi! I wanted to do a division function but the catch is I will not use "/". This is what I got and so far this prints out "undefined" and if I stated x = 0 it will print out "0".
I fixed some problems with your code:
function division(num1, num2){
var difference = num1-num2; // difference is now a local variable
var x = 0; // x should be initialized
while(difference > 0){
difference = difference-num2; // difference should change, not always be num1-num2
x = x + 1;
}
console.log("Quotient" + x);
console.log("Remainder" + (difference+num2));
}
http://jsbin.com/UQIqejo/1/edit
You still have some problems with the algorithm itself, as num2 being less than or equal to 0 will result in an infinite loop, but i expect finding those problems is part of the fun.
EDIT: Smaller version of the same code:
function divisionSmall(a,b) {
var x = 0;
while ((a-=b) > 0) x++;
console.log('Quotient', x);
console.log('Remainder', a+b);
}
EDIT2: Correct division:
function divisionSmall(a,b) {
var x = 0;
while ((a-=b) > 0) x++;
return [x, a+b];
}
function divisionCorrect(a,b) {
var ans;
if (b === 0) return ['INF', 0];
if ((a > 0) && (b > 0)) {
return divisionSmall(a,b);
}
if ((a > 0) && (b < 0)) {
ans = divisionSmall(a,-b);
return [-ans[0], ans[1]];
}
if ((a < 0) && (b > 0)) {
ans = divisionSmall(-a,b);
return [-ans[0] - 1, b-ans[1]];
}
if ((a < 0) && (b < 0)) {
ans = divisionSmall(-a,-b);
return [ans[0] + 1, -b-ans[1]];
}
}
console.log(divisionCorrect(11,3)); // 3, 2
console.log(divisionCorrect(11,-3)); // -3, 2
console.log(divisionCorrect(-11,3)); // -4, 1
console.log(divisionCorrect(-11,-3)); // 4, 1
There is still the challenge of doing the logic without ifs :). Good luck.
If your doing numbers their is a simpler way to do this using recursion:
function divide(num,denom) {
if (num < denom) return 0;
return (1 + divide(num - denom, denom));
}
For negative numbers you would have to extend this to track if numbers were less than 0. Also, while concise and neat, this breaks down for large numerators and small denominators as the max call stack size will be exceeded.
I believe your issue is with your while loop. If the subtraction method returns a negative number it will not compute.
User Math.abs to get absolute value.
<script>
function division(num1, num2){
var difference = Math.abs(parseFloat(subtraction(num1, num2)));
var x = 0;
while(difference > 0){
difference = difference-num2;
x = x + 1;
}
document.writeln("Quotient" + x);
}
function subtraction(num1, num2){
var num3;
num3 = num1 - num2;
document.writeln("Difference "+ num3); return (num3);
}
</script>

Categories

Resources