Reputation: 369
I think that this code works but in the challenge they asking me to return "15511210043330985984000000" instead of "1.5511210043330984e+25" I don't understand what could be the problem. I've tried putting "BigInt" before my result but that gives me something like "15511210043330985984000000n" this "n" at the end of every number.
function extraLongFactorials(n) {
let result = 1;
for(let i = n; i >= 1; i--) {
result *= i;
}
return result;
}
console.log(extraLongFactorials(25));
// should be 15511210043330985984000000
Upvotes: 2
Views: 2249
Reputation: 51
let extraLongFactorials = (n) => {
let mult = 1
while (n >= 1) {
mult = BigInt(mult) * BigInt(n)
--n
}
console.log(BigInt(mult).toString())
}
Upvotes: -1
Reputation: 333
an easy and clean solution is:
let memoization = [BigInt(0), BigInt(1)];
const factorial = num => (typeof memoization[num] !== 'number')
? ((num - BigInt(1)) > 0
? (num * factorial(num - BigInt(1)))
: BigInt(1)
)
: memoization[num]
console.log(String(factorial(BigInt(n))));
Upvotes: 0
Reputation: 1
an easy solution for this challenge:
function extraLongFactorials(n) {
let factorial = BigInt(1);
for (let i = BigInt(2); i <= n; i++) {
factorial *= i;
}
return factorial.toString();
}
Upvotes: 0
Reputation: 11
Javascript recursive solution
function extraLongFactorials(n) {
const factorial = (int) => {
const bigInt = BigInt(int)
return bigInt === 0n ? 1n : bigInt * factorial(bigInt - 1n)
}
console.log(factorial(n).toString())
}
extraLongFactorials(25)
Upvotes: 1
Reputation: 369
Well, I found this solution. It is quite close to what @undg was saying but a little different that is the answer I was expecting.
function extraLongFactorials(n) {
n = BigInt(n)
let result = BigInt(1);
for(let i = n; i >= 1; i--) {
result *= i;
}
return result.toString();
}
console.log(extraLongFactorials(25)); // 15511210043330985984000000
Upvotes: 3
Reputation: 825
Use BigInt() followed by toString()
BigInt(Number.MAX_VALUE).toString()
//'179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368'
Upvotes: 0