JavaScript factorial function returning scientific notation instead of full number

I’m working on a coding challenge where I need to calculate really big factorials. My function seems to work, but it’s giving me the answer in scientific notation. The challenge wants the full number as a string.

Here’s my current code:

function bigFactorial(num) {
  let answer = 1;
  while (num > 0) {
    answer *= num;
    num--;
  }
  return answer;
}

console.log(bigFactorial(25));

This outputs 1.5511210043330984e+25. But the challenge expects 15511210043330985984000000.

I tried using BigInt, but that adds an ‘n’ at the end of the number. Any ideas on how to get the full number as a string without scientific notation or extra characters?

hey, i had a similar problem. try using the toString() method with a radix of 10. like this:

function bigFactorial(num) {
let answer = 1n;
while (num > 0) {
answer *= BigInt(num);
num–;
}
return answer.toString(10);
}

this should give u the full number as a string. hope it helps!

I encountered a similar issue when working on a project involving large number calculations. The solution lies in using a custom BigInteger implementation. Here’s what I found effective:

Create a BigInteger class that stores numbers as arrays of digits. Implement basic arithmetic operations like addition and multiplication for this class. Then, use this custom class in your factorial function.

This approach allows for precise calculations with arbitrarily large numbers, avoiding the limitations of JavaScript’s native number type. It’s more complex than using built-in types, but it gives you full control over the number representation and operations.

Remember to convert the final result to a string before returning it. This method ensures you get the exact output required by your coding challenge.

I’ve tackled this issue before in a project. The problem is that JavaScript has limitations with large numbers. Here’s what worked for me:

Instead of using regular numbers, use strings to represent your factorial. Implement a custom multiplication function that works with string representations of numbers. This way, you can handle arbitrarily large numbers without running into precision issues or scientific notation.

Here’s a rough outline:

  1. Start with ‘1’ as a string
  2. For each number in the factorial, multiply your current result string by that number
  3. Implement a string multiplication function that does digit-by-digit multiplication

It’s a bit more complex, but it’ll give you the exact result you need. The key is thinking of the numbers as strings from the start, not trying to convert them later. Hope this helps!