Wednesday, June 9, 2010

Factorial of large numbers


using System;


using System.Collections.Generic;


using System.Linq;


using System.Text;


 


namespace ConsoleApplication1


{


    class Program


    {


        static void Main(string[] args)


        {


            string s1 = "30";


            int num1 = int.Parse(s1);


            int num2 = num1 - 1;


            //string s2 = num2.ToString();


            string ans = multiply(s1, num2);


            while (num2 > 1)


            {


                num2--;


                //s2 = num2.ToString();


                ans = multiply(ans, num2);


            }


            Console.WriteLine(ans);


        }


        static string multiply(string s1, int s2)


        {


            int length1 = s1.Length;


            int[] arr = new int[length1];


            for (int i = 0; i < length1; i++)


            {


                string str = "";


                str = str + s1[i];


                arr[i] = int.Parse(str);


            }


            int carry = 0;


            string answer = "";


            //Multiplying the second number(full) to the first number(digitwise).


            for (int i = length1-1; i >= 0; i--)


            {


                int ans = arr[i] * s2 + carry;


                int dig = ans % 10;


                carry = ans / 10;


                answer = answer + dig.ToString();


            }


            //Prefixing the remaining carry to the answer.


            if (carry != 0)


            {


                while (carry > 0)


                {


                    int m = carry % 10;


                    answer = answer + m.ToString();


                    carry = carry / 10;


                }


            }


            string Finalanswer = "";


            //Reversing the answer string to get the Finalanswer.


            for (int i = answer.Length - 1; i >= 0; i--)


            {


                Finalanswer = Finalanswer + answer[i];


            }


            return Finalanswer;


        }


    }

}

No comments:

Post a Comment