以下是一个经典的大整数 PI 值计算程序。
程序代码:
程序代码:#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
const int LONG_TIME = 4000;
char *p;
char *t;
int q;
void l_add()
{
int j;
for ( j = q; j >= 0; j-- ) {
if ( t[j] + p[j] > 9 ) {
p[j] += t[j] - 10;
p[j - 1] += 1;
} else
p[j] += t[j];
}
}
void l_sub()
{
int j;
for ( j = q; j >= 0; j-- ) {
if ( p[j] < t[j] ) {
p[j] -= t[j] - 10;
p[j - 1] -= 1;
} else
p[j] -= t[j];
}
}
void l_mul( int multiplier )
{
int b;
int i;
int carry = 0, digit = 0;
for ( i = q; i >= 0; i-- ) {
b = ( t[i] * multiplier + carry );
digit = b % 10;
carry = b / 10;
t[i] = digit;
}
}
/* t[] /= l */
void l_div( int divisor )
{
int i, b;
int quotient, remainder = 0;
for ( i = 0; i <= q; i++ ) {
b = ( 10 * remainder + t[i] );
quotient = b / divisor;
remainder = b % divisor;
t[i] = quotient;
}
}
void div4()
{
int i, c, d = 0;
for ( i = 0; i <= q; i++ ) {
c = ( 10 * d + p[i] ) / 4;
d = ( 10 * d + p[i] ) % 4;
p[i] = c;
}
}
void mul4()
{
int i, c, d;
d = c = 0;
for ( i = q; i >= 0; i-- ) {
d = ( p[i] * 4 + c ) % 10;
c = ( p[i] * 4 + c ) / 10;
p[i] = d;
}
}
int tiszero()
{
int k;
for ( k = 0; k <= q; k++ )
if ( t[k] != 0 )
return FALSE;
return TRUE;
}
void l_arctan( int s )
{
int n;
t[0] = 1;
l_div( s ); /* t[] = 1/s */
l_add();
n = 1;
do {
l_mul( n );
l_div( s * s );
l_div( n += 2 );
if ( ( ( n - 1 ) / 2 ) % 2 == 0 )
l_add();
else
l_sub();
} while ( !tiszero() );
}
int main( int argc, char *argv[] )
{
DWORD startime, endtime;
int i;
if ( argc == 2 ) {
q = atoi( argv[1] );
} else {
printf( "Usage: pi [precision]" );
return 1;
}
if ( q < 0 ) {
printf( "Precision was too low, running with precision of 0." );
q = 0;
}
if ( q > LONG_TIME ) {
printf( "Be prepared to wait a while..." );
}
// Compute one more digit than we display to compensate for rounding
q++;
p = malloc( q + 1 );
t = malloc( q + 1 );
if ( !p || !t ) {
printf( "Cannot allocate memory\n" );
return 2;
}
memset( p, 0, q + 1 );
memset( t, 0, q + 1 );
/* compute pi */
startime = GetTickCount();
l_arctan( 2 );
l_arctan( 3 );
mul4();
endtime = GetTickCount();
// Return to the number of digits we want to display
q--;
/* print pi */
printf( "pi = %d.", p[0] );
for ( i = 1; i <= q; i++ )
printf( "%d", p[i] );
printf( "\n%d ms to compute pi with a precision of %d digits.",
endtime - startime, q );
return 0;
}

