Difference between revisions of "Category:C"

From CodeCodex

(compute digits of pi)
(Replaced content with "This is a list of code snippets in the C programming language. Category:Programming languages")
 
Line 1: Line 1:
===C===
+
This is a list of code snippets in the C programming language.
Complete C99 code:
+
Some corrections to posted earlier algorithm/program
+
<pre class="c">
+
#include "stdio.h"
+
#include "stdlib.h"
+
  
#define SCALE 10000
+
[[Category:Programming languages]]
#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; //safe ver is sum=(long int)(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) {
+
//  printf("Not enough memory :(");
+
//  return(0);
+
// }
+
//
+
// in general n, digits and index vars i,j may be declared as long int
+
// just for geeks :D needing more than 18k digits
+
 
+
 
+
 
+
</pre>
+

Latest revision as of 19:58, 9 April 2013

This is a list of code snippets in the C programming language.

Pages in category "C"

The following 70 pages are in this category, out of 70 total.

A

B

C

D

E

F

G

H

I

J

K

M

N

O

P

Q

R

S

T

W