[ create a new paste ] login | about

Link: http://codepad.org/AhRSeykS    [ raw code | output | fork ]

C, pasted on Nov 9:
#include <stdio.h> 
#define ABS( x ) (((x)<0)?-(x):(x)) 
double dnpow( double x, int n ) 
{ return n > 0 ? x * dnpow( x, n - 1 ) : 1.0; } 
double af( double p, int n ) 
{ 
int k; 
double f = p * p / 6.0; 
for( k=1; k<=n; ++k ) 
f -= 1.0 / ( (double)k * k ); 
return ABS( f ); 
} 
int find_n( double p, double e, int n_min, int n_max ) 
{ 
int n_mid = ( n_min + n_max ) / 2; 
return n_min + 1 == n_max ? n_max : af( p, n_mid ) < e ? find_n( p, e, n_min, n_mid ) : find_n( p, e, n_mid, n_max ); 
} 
int main() 
{ 
int i, n = 1; 
double e, p = 0; 
printf( "Input the volume of error: " ); 
scanf( "%lf", &e ); 
for( i=0; i<=100; ++i ) 
p += 4.0 * dnpow( -1.0, i ) * ( dnpow( 1.0 / 2.0, 2 * i + 1 ) + dnpow( 1.0 / 3.0, 2 * i + 1 ) ) / ( 2 * i + 1 ); 
printf( "Pi is %.8f.\n\n", p ); 
for( n=1; ; n*=2 ) if( af( p, n ) < e ) break; 
n = n == 1 ? n : find_n( p, e, n / 2, n ); 
printf( "the smallest integer N is %d.\n", n ); 
return 0; 
} 


Output:
1
Timeout


Create a new paste based on this one


Comments: