Skip to content

Instantly share code, notes, and snippets.

@ellemedit
Last active October 2, 2016 14:03
Show Gist options
  • Save ellemedit/97bbac827e5a75d393ee3083e4fdd603 to your computer and use it in GitHub Desktop.
Save ellemedit/97bbac827e5a75d393ee3083e4fdd603 to your computer and use it in GitHub Desktop.
#include <stdio.h>
int result[2][2];
void multiplyTwoTwoMatrix(int result[][2], int m1[][2], int m2[][2]) {
result[0][0] = (m1[0][0] * m2[0][0] + m1[0][1] * m2[1][0]) % 10000;
result[0][1] = (m1[0][0] * m2[0][1] + m1[0][1] * m2[1][1]) % 10000;
result[1][0] = (m1[1][0] * m2[0][0] + m1[1][1] * m2[1][0]) % 10000;
result[1][1] = (m1[1][0] * m2[0][1] + m1[1][1] * m2[1][1]) % 10000;
}
void improvedFibonacci(int n) {
if (n <= 0) {
result[0][0] = result[1][1] = 1;
result[1][0] = result[0][1] = 0;
}
else if (n == 1) {
result[0][0] = result[0][1] = result[1][0] = 1;
result[1][1] = 0;
}
else {
int matrix[2][2];
if (n % 2 == 0) {
improvedFibonacci(n / 2);
int base[2][2];
base[0][0] = result[0][0];
base[0][1] = result[0][1];
base[1][0] = result[1][0];
base[1][1] = result[1][1];
multiplyTwoTwoMatrix(result, base, base);
}
else {
improvedFibonacci((n - 1) / 2);
int baseMatrix[2][2] = { 1,1,1,0 };
int base[2][2];
base[0][0] = result[0][0];
base[0][1] = result[0][1];
base[1][0] = result[1][0];
base[1][1] = result[1][1];
multiplyTwoTwoMatrix(result, base, base);
base[0][0] = result[0][0];
base[0][1] = result[0][1];
base[1][0] = result[1][0];
base[1][1] = result[1][1];
multiplyTwoTwoMatrix(result, base, baseMatrix);
}
}
}
int main() {
int n;
// repeat till input is -1
while (scanf("%d", &n) != 0 && n != -1) {
int matrix[2][2];
improvedFibonacci(n);
printf("%d\n", result[0][1] % 10000);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment