On May 15, 6:11 am,
bl0ckedusers...@gmail.com wrote:
> On Sunday, May 13, 2012 11:42:42 AM UTC-4, ashu wrote:
> > i need to know how to calculate big numbers i.e. factorial
> > of 100.
I.e. means 'that is'. It's possible you meant e.g. meaning 'for
example'.
The simplest way of working with big numbers is to store them
in arrays and use traditional pencil and paper methods to do
calculations. The example below just stores digits 0..9 in a
character array.
> > i google and found a solution
> > but didn`t understand how it is done.
It's hard to give advice on how to understand something if you
haven't told us what it was you didn't understand.
> > and some others solution is using some library .
That's because using existing libraries is often quicker and
easier than re-inventing the wheel.
> > but i actually want to develop a solution witch i understand.
> > kindly give me some logic?
> > atleast i need to know how to start with.
>
> It is C code to calculate big factorials. It requires no
> special libraries, as it implements the "big number" code
> itself.
>
> big-factorial.c
>
> #include <stdio.h>
> #include <stdlib.h>
> #include <string.h>
>
> #define DIG 1000000 /* maximum number of digits */
I got bored after a minute of no output. Note that 100!
has nowhere near this number of digits.
> void bignum_add(char*, char*);
> void bignum_put(char*);
>
> int main(int argc, char** argv)
> {
> char bignum_1[DIG] = {0};
> char bignum_2[DIG] = {0};
I have a tentative rule not to allocate more than 256 bytes of
automatic storage if possible.
<snip>
Since we only need a factorial, and since we only need decimal
output, here's a simple way of calculating in blocks of 4 digits
at a time. I'll leave it as an exercise to modify it to work on
numbers higher than 9999!
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int i;
size_t j, fc;
unsigned long n, N;
unsigned long a;
unsigned short *f = malloc(sizeof *f);
if (!f) return 0;
for (i = 1; i < argc; i++)
{
N = strtoul(argv[i], 0, 10);
if (N > 9999) return 0;
fc = 1;
*f = 1; /* f = 1 */
for (n = 2; n <= N; n++)
{
/* f *= n */
for (a = 0, j = 0; j < fc; j++)
{
a = f[j] * n + a;
f[j] = a % 10000;
a /= 10000;
}
if (a)
{ /* left over carry - expand the buffer */
fc++;
f = realloc(f, fc * sizeof *f);
if (!f) return 0;
f[j] = a;
}
}
/* backwards print the little endian result */
for (j = fc; j-- > 0; )
printf(j == fc - 1 ? "%hu" : "%04hu", f[j]);
putchar('\n');
}
return 0;
}
--
Peter