Category:C
From CodeCodex
[edit] C
Complete C99 code: Some corrections to posted earlier algorithm/program
#include "stdio.h" #include "stdlib.h" #define SCALE 10000 #define ARRINIT 2000 //mrhm: //SCALE*ARRINIT = 20000000 >> max 2 byte int !, //so same variables should be long int instead of int void pi_digits(int digits) { long int carry = 0; long int arr[digits + 1]; for (int i = 0; i <= digits; ++i) arr[i] = ARRINIT; for (int i = digits; i > 0; i-= 14) { long int sum = 0; for (int j = i; j > 0; --j) { sum = sum * j + SCALE * arr[j]; arr[j] = sum % (j * 2 - 1); sum /= j * 2 - 1; } printf("%04d", carry + sum / SCALE); carry = sum % SCALE; } } int main(int argc, char** argv) { int n = argc == 2 ? atoi(argv[1]) : 100; //mrhm: //algorithm(program) outputs 4 digits each time and works on 14 digits group //can be seen after carefully analyzing //so n=(int)(n*14/4) n=(int)(n*14/4); pi_digits(n); return 0; } //mrhm: //and finally works correctly :D, but should be used carefully for big number of //digits. //It seems be better idea to use: // long int *arr; // ... // arr=malloc(sizeof(long int)*(digits+1)); // if (arr==NULL) //
Pages in category "C"
The following 53 pages are in this category, out of 53 total.