CodeChef – Small Factorials

using System;
using System.Collections.Generic;
using System.Numerics;

public class Program
{
	public static void Main()
	{
		int dataSize = int.Parse(Console.ReadLine());
		List<BigInteger> data = new List<BigInteger>();
		
		for(int i = 0; i < dataSize; i++)
		{
			data.Add(BigInteger.Parse(Console.ReadLine()));
		}
		
		foreach(BigInteger n in data)
		{
			Console.WriteLine(CalculateFactorial(n));
		}
	}

	public static BigInteger CalculateFactorial(BigInteger n)
	{
		if(n > 1)
		{
			n = n * CalculateFactorial(n-1);
			return n;
		}
		else
		{
			return n;
		}
	}
}

So here’s a proper factorial calculator as opposed to the previous post entitled ‘Factorials.’ This code actually calculates the factorial of a number. I have to admit though that this code was not accepted by CodeChef because there is a compiling error due to the fact that CodeChef uses an older version of .Net in which the namespace Numerics does not exist. You can do this with doubles fine but the judge on CodeChef doesn’t accept scientific notation. And if you convert the scientific notation with format specifiers, the number still gets rounded up too much. Apparently there is a way to do this problem without Numerics and the BigInteger data type but I’m pretty satisfied with my solution regardless.

Here’s a link to the problem.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s