factorial

Discuss Computer Science and Programming related problems

Moderators:Labib, bristy1588

User avatar
amlansaha
Posts:100
Joined:Tue Feb 08, 2011 1:11 pm
Location:Khulna, Bangladesh
Contact:
factorial

Unread post by amlansaha » Mon Jan 09, 2012 7:28 pm

how can i calculate the factorial of a number>20 ?
অম্লান সাহা

Corei13
Posts:153
Joined:Tue Dec 07, 2010 9:10 pm
Location:Chittagong

Re: factorial

Unread post by Corei13 » Mon Jan 09, 2012 8:08 pm

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.
ধনঞ্জয় বিশ্বাস

mekanix
Posts:1
Joined:Wed Jan 18, 2012 8:34 pm

Re: factorial

Unread post by mekanix » Wed Jan 18, 2012 8:57 pm

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

qeemat
Posts:11
Joined:Thu Feb 16, 2012 6:43 pm

Re: factorial

Unread post by qeemat » Fri Feb 17, 2012 4:35 pm

#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;
}

Hasib
Posts:238
Joined:Fri Dec 10, 2010 11:29 am
Location:খুলনা, বাংলাদেশ
Contact:

Re: factorial

Unread post by Hasib » Sat Mar 10, 2012 12:50 am

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);
?>
A man is not finished when he's defeated, he's finished when he quits.

Post Reply