Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
C code for calculating Pi.
#include <iostream>
#include <conio.h>
#include <windows.h>
const int N = 50000;
const int Len = 10 * N / 3;
int J, K, Q, Nines, PreDigit;
LARGE_INTEGER StartTime, EndTime, Frequency;
int PiArray[Len + 1]; // 0 .. Len
int OneLoop(int aIndex)
{
int x, result;
aIndex = aIndex * 10 / 3 + 16;
aIndex = (aIndex > Len) ? Len : aIndex;
result = 0;
do {
x = 10 * PiArray[aIndex] + result * aIndex;
result = x / (2 * aIndex - 1);
PiArray[aIndex] = x - result * (2 * aIndex - 1);
aIndex--;
} while(aIndex > 0);
return result;
};
int main()
{
QueryPerformanceFrequency(&Frequency);
QueryPerformanceCounter(&StartTime);
for(J = 1; J <= Len; J++) {
PiArray[J] = 2;
}
PreDigit = 0;
Nines = 0;
for(J = 1; J <= N; J++) {
Q = OneLoop(N - J);
PiArray[1] = Q % 10;
Q = Q / 10;
if(9 == Q) {
Nines = Nines + 1;
}
else {
if(10 == Q) {
//std::cout << PreDigit + 1;
for(K = 1; K <= Nines; K++) {
//std::cout << 0;
}
PreDigit = 0;
Nines = 0;
}
else {
//std::cout << PreDigit;
PreDigit = Q;
if(Nines != 0) {
for(K = 1; K <= Nines; K++) {
//std::cout << 9;
Nines = 0;
}
}
}
}
}
//std::cout << PreDigit;
QueryPerformanceCounter(&EndTime);
std::cout << std::endl;
std::cout << "C takes time " << (EndTime.QuadPart - StartTime.QuadPart) * 1.0f / Frequency.QuadPart << std::endl;
_getch();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment