Page 1 of 1

factorial

Posted: Mon Jan 09, 2012 7:28 pm
by amlansaha
how can i calculate the factorial of a number>20 ?

Re: factorial

Posted: Mon Jan 09, 2012 8:08 pm
by Corei13
You can input a large number as a string and store it in a array. It'll be helpfull if you know struct(just Google)
Here's a sample elementary code ( in C++, I don't know C that much :? ) :

Code: Select all

#define MAXS something // 'something' is the maximum number of digits you need
struct BigInt
{
    int digit[MAXS]; // let N is a big integer, then digit[i] is it's (i+1)'th digit
    BigInt ( string S = "" ) \\initializing
    {
        for ( int i=0;i<S.size();++i)
        {
            digit[i] = S[i] - '0';
        }
        for ( int i = S.size();i<MAXS;i++) digit[i] = 0;
    }
    BigInt ()
    {
        BigInt("");
    }
    BigInt add ( BigInt B )
    {
        int carry = 0;
        BigInt C;
        for( int i =0; i< MAXS;i++)
        {
             C.digit[i] = B.digit[i] + digit[i] + carry;
             carry = C.digit[i]/10;
             C.digit[i] %= 10;
        }
        return C;
    }
   
   BigInt substract ( BigInt B )
   {
           //code something that substract
   }
   BigInt multiply ( BigInt B )
   {
            //code something that multiply
   }
  //other codes.....
};
Now to add BigInt A & B:
C = A.add(B);
or to multiply:
C = A.multiply(B);

and so on.

Re: factorial

Posted: Wed Jan 18, 2012 8:57 pm
by mekanix
It can be done very easily using python with a short code like this:

Code: Select all

def factorial(m):
    if x==1:
        return 1
    else:
        return m*factorial(m-1)

print factorial(m)
It's called 'recursion' in python. It seems great to write some short codes like this one to find something huge!

in fact you can find the factorial of verrry large numbers! :D

Re: factorial

Posted: Fri Feb 17, 2012 4:35 pm
by qeemat
#include <numeric>
#include <functional>

int factorial(int num) {
int *array = new int[num];
for (int i = 0; i < num; i++)
array = i+1;
int result = std::accumulate(array, array+num, 1, std::multiplies<int>());
delete [] array;
return result;
}

Re: factorial

Posted: Sat Mar 10, 2012 12:50 am
by Hasib
Life is short!! We need PHP :D

Code: Select all

<?php

function fac($int)
{
if($int==1)
   return 1;
else
   return $int*fac($int-1);
 }
$number="500"; /as u wish
echo fac($number);
?>