Perl and Big Number

175 views Asked by At

For calculating nCr [ i.e. n ! / ( r ! * ( n-r )! ) ], written the below code.

Perl code:

($i,$j)=(1000,100);
print fact($i)/(fact($j)*(fact($i-$j)));
sub fact{
    return 1 if $_[0]<=1;
    return $_[0]*fact($_[0]-1);
}

which is giving output as "-NaN" but,

same logic code in python gives correct result.

Python code:

def fact(x):
    if x <= 1:
        return 1
    return x*f(x-1)
v,y = 1000,100
print fact(v)/(fact(y)*fact(v-y))

Kindly let me know what changes I have to made in perl code to make it work for bigger numbers.(And also I tried to use "bigint" too, But didnot worked)

Edit:

Thank you all for the response.

Sorry that, I have missed ; and -1.

I think bigint is dependent on machine configuration

http://www.perlmonks.org/?node_id=906757

2

There are 2 answers

0
Borodin On

I don't know what you did, but use bigint works fine

As ikegami said, the code that you posted doesn't even compile, so you're making it as hard as you can to help you

use strict;
use warnings;

use bigint;

my ($i, $j) = (1000, 100);

no warnings 'recursion';

print fact($i) / ( fact($j) * fact($i-$j) ), "\n";

sub fact{
    $_[0] <= 1 ? 1 : $_[0] * fact($_[0]-1);
}

output

63850511926305130236698511142022274281262900693853331776286816221524376994750901948920974351797699894319420811933446197797592213357065053890

Why would you want that number, anyway?

0
anuj rana On

try this I think that will resolve the problem

use bignum;
($i,$j)=(1000,100);
print fact($i)/(fact($j)*(fact($i-$j)));
sub fact{
    return 1 if $_[0]<=1;
    return $_[0]*fact($_[0]-1);
}