Factorial function calling itself [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I came across this function which works fine for the purpose but I can't get why factorial can be called in a factorial() function. Can someone explain to me.
function factorial(n) {
if(n ==0) {
return 1;
}else{
return factorial(n-1) *n;
}
}
console.log(factorial(8));
//Logs 40320

It's called recursion. What's recursion?
Recursion is simply when a function calls itself.
You can find out more of it in JavaScript here

This is a Software Engineering (Data Structure and Algorithms) concept called recursion.
Recursion is the programming concept where a function calls itself. In the case of the factorial function, from observation, for all integers n greater than 1, factorial(n) = n * factorial(n-1). E. g. factorial(5) = 5 * factorial(4)
this means, in the implementation, the function can call itself with (n-1) and multiply the result by n.
You can read more from here.
Recursion has advantages and disadvantages.

please read this code it's work.
function factorialize(num) {
// Step 1. Create a variable result to store num
var result = num;
// If num = 0 OR num = 1, the factorial will return 1
if (num === 0 || num === 1)
return 1;
// Step 2. Create the WHILE loop
while (num > 1) {
num--; // decrementation by 1 at each iteration
result = result * num; // or result *= num;
/*
num num-- var result result *= num
1st iteration: 5 4 5 20 = 5 * 4
2nd iteration: 4 3 20 60 = 20 * 3
3rd iteration: 3 2 60 120 = 60 * 2
4th iteration: 2 1 120 120 = 120 * 1
5th iteration: 1 0 120
End of the WHILE loop
*/
}
// Step 3. Return the factorial of the provided integer
return result; // 120
}
console.log(factorialize(5));

Related

Creating IF statement inside math.Random function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am trying to create code that if we generate number between 20 and 120 and the generated number is >= than 100 then we want to reduce by 20. I dont want to create multiple random numbers..Can someone help ??
my basic math.rand function -
function randomNumber(min, max) {
return Math.random() * (max - min) + min;
}
the code i tried to make
randomNumber(20,120);
if(randomNumber >= 100){
return randomNumber - 20;
}
message.reply(randomNumber);
In messages it display function randomNumber(min, max) { etc...
Store the result of the randomNumber function in a variable like this:
let number = randomNumber(20,120);
if(number >= 100){
number -= 20;
}
message.reply(number);
In JavaScript, you add () to run a function. Without those parentheses, you are just returning the code itself. When you state if(randomNumber >= 100), you aren't comparing the value that the function returns, rather the function itself.
When you call randomNumber(20,120) it returns a number, but you don’t put that number in any variable, so it just gets lost. And then you return randomNumber, which is a function, that’s why it prints out the content of the function.
To avoid that, create a variable containing the random number, like so:
let x = randomNumber(20,120);
if(x >= 100){
x -= 20;
}
message.reply(x);
Just save the result of your function in a variable and then check if that variable is >= 100 and if it is reduce it by 20 using a simple ternary operator.
function randomNumber(min, max) {
return Math.random() * (max - min) + min;
}
number = randomNumber(20,120);
number = (number < 100) ? number : number -20;
console.log(number);

Calculating trailing zero in javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
How do i calculate the number of trailing zeros in a factorial of a given number.
N! = 1 * 2 * 3 * 4 ... N
Any Help on this?
Because zeros come from factors 5 and 2 being multiplied together, iterate over all numbers from 1 to the input number, adding to a cumulative count of fives and twos whenever those factors are found. Then, return the smaller of those two counts:
function zeroCount(n) {
let fives = 0;
let twos = 0;
for (let counter = 2; counter <= n; counter++) {
let n = counter;
while (n % 2 === 0) {
n /= 2;
twos++;
}
while (n % 5 === 0) {
n /= 5;
fives++;
}
}
return Math.min(fives, twos);
}
console.log(zeroCount(6)); // 720
console.log(zeroCount(10)); // 3628800
It is very simple, This will help you.
function TrailingZero(n)
{
var c = 0;
for (var i = 5; n / i >= 1; i *= 5)
c += parseInt(n / i);
return c;
}
Let me know if you need help to understand this function.

Multiplication in for loop [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am new to JS and I am completely stuck with this simple thing and I would really like to understand this and continue further with learning.
I have this chunk of code:
var power = function(base, exponent) {
var result = 1;
for (var count = 0; count < exponent; count++) {
result *= base;
}
return result;
};
console.log(power(2, 10));
// Result is: 1024
A result in the console will be 1024
If I change values into:
console.log(power(1, 10));
// Result is: 1
But if I change into:
console.log(power(3, 10));
// Result is: 59049
I will get a result of 59049.
So, how I got this result of 59049? How I got a result of 1024? How I got a result of 1? How does all this thing work?
I would really appreciate if someone can explain it to me on as simplest and dummies way as possible :)
Thanks!
That's because
2 to the power of 10 (or 1 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2) equals 1024
and
1 to the power of 10 (or 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1) equals 1
and
3 to the power of 10 (or 1 * 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3) equals 59049
If you supply your function with a base and an exponent, the function will do the following:
power(2, 0) yields 1 because exponent is 0 and the function immidiately returns result (which is 1) without entering the loop.
power(2, 1) yields 2 because result (which is 1) is multiplied once with base (which is 2) in your loop thus resulting in 1 * 2 = 2
power(2, 2) yields 4 because result (which is 1) is multiplied twice with base (which is 2) in your loop thus resulting in 1 * 2 * 2 = 4
power(2, 3) yields 8 because result (which is 1) is multiplied three times with base (which is 2) in your loop thus resulting in 1 * 2 * 2 * 2 = 8

javascript program without using math. pow, find power of any number using for loop [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 months ago.
Improve this question
I need to know the code built in for the syntax math.pow(x,y). Actually I used the syntax to find exponent of any number... e.g.
var e = Math.pow(-3, 3); yields -27 but couldn't find out the program behind this... Help me please
If you know what power means..
multiplying the number x n times where x is base and n is exponent.
So you just have to repeat the same thing over and over - and that's why loops are for:
var sum = 1; //note that it's not zero!
for (int i=0;i<n;i++) { //loops n times
sum = sum * x; //on each loop multiplies sum by base number
}
Did you mean alternative for Math.pow? Here is one way with simple loop.
function pow(base,power) {
var p = 1;
for (var i=0; i<power; i++) {
p *= base;
}
return p;
}
You can also use recursion to solve this kind of challenge. Beware that recursion has the disadvantage of increasing space complexity as compared to a for-loop.
function pow(base, power) {
if (power === 1) return base * power
return base * pow(base, power - 1)
}
This is a better way to calculate power of a number with recursion:
function power(base, exp) {
if(exp === 0){
return 1;
}
return base * power(base, exp - 1);
}
You can try this:
function pow(n, e) {
let num = n;
for (let i = 1; i < e; i++) {
num *= n;
}
return num;
}
console.log(pow(-3, 3));
It will give you the required result.

how to understand javascript for loop? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have this simple javascript code:
function power(base, exponent) {
var result = 1;
for (var count = 0; count < exponent; count++)
result = result * base;
return result;
}
power(2, 10);
but it s hard for me to understand what is the relationship between for loope and the result in the for loop. Can anyone describe the process in here? I know that the answer is 1024 and that it is 2*2*2*2*2*2*...... but it is har for me to understand how for and result is related. result is always 1? Or somehow it grabs the updated version from the loop? Thank you!
Say I pass power(2, 10). Here's how it's going to run, with each iteration:
i | result
--+-------
- | 1
0 | 1 * 2 = 2
1 | 2 * 2 = 4
2 | 4 * 2 = 8
.
.
.
9 | 512 * 2 = 1024
However, the numbers array is redundant. You'll need to check against exponent (i < exponent)
numbers is totally unnecessary. the length of the array [0....x] is x. So your for loop is really for (var i = 0; i < 10; i++). Hope that sorts it out. Also, you don't want to go to 10, but rather to exponent. Try:
for (var i = 0; i < exponent; i++)
why do you not write this?
function power(base, exponent) {
var result = 1;
for (var i = 0; i < exponent; i++)
result = result * base;
return result;
}
or there is also e javascript-integrated way
Math.pow(base, exponent);
when you call a function with power(2,10) you give variable "base" value of 2, and then it multiplies the result (which is 1) by 2 for 10 times, I see no use of that second variable "exponent"

Categories