I am dealing with a question from hackerrank. I am not able to display correct output i don't know which data type to use in this program.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution
{
static void Main(String[] args)
{
double n = int.Parse(Console.ReadLine());
double factorial = 1;
for (int i = 1; i <= n; i++)
{
factorial *= i;
}
Console.WriteLine(factorial);
}
}
I am getting this output
1.5511210043331E+25
But Expected output is
15511210043330985984000000
I am thinking to use long but i don't know how. Please suggest me how to deal with it.
Thanks in advance.
As someone suggested in the comments, using BigInteger is also a good idea.
Here is documentation on BigInteger: https://msdn.microsoft.com/en-us/library/system.numerics.biginteger(v=vs.110).aspx
BigInteger Solution:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics; // This is important
class Solution
{
static void Main(String[] args)
{
int n = int.Parse(Console.ReadLine()); // No reason to accept a double here
BigInteger factorial = 1;
for (int i = 1; i <= n; i++)
{
factorial *= i;
}
Console.WriteLine(factorial.ToString());
}
}