Fibonacci function
int Fibonacci(int n) { int a = 1, b = 1, c, i; for (i=3; i<=n; i++) {c = b; b += a; a = c; } return b; }
DZone Snippets > Minimiscience > math
12116 users tagging and storing useful source code snippets
Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
int Fibonacci(int n) { int a = 1, b = 1, c, i; for (i=3; i<=n; i++) {c = b; b += a; a = c; } return b; }
int factorial(int x) { int fac = 1; for (int i=2; i<=x; i++) fac *= i; return fac; }
#define nCr(n, r) (factorial(n) / factorial(n-r) / factorial(r)) #define nPr(n, r) (factorial(n) / factorial(n-r))
int modInverse(int a, int n) { int i = n, v = 0, d = 1; while (a>0) { int t = i/a, x = a; a = i % x; i = x; x = d; d = v - t*x; v = x; } v %= n; if (v<0) v = (v+n)%n; return v; }
int gcd(int x, int y) { int a, b; if (x<y) {a = y; b = x; } else if (x>y) {a = x; b = y; } else {return x; } do { int r = a % b; a = b; b = r; } while (b != 0); return a; }
#include <stdio.h> #include <stdlib.h> #include <math.h> int main(int argc, char** argv) { int qty = (argc > 1) ? (int) strtol(argv[1], NULL, 10) : 100; if (qty < 3) qty = 100; unsigned int primes[qty]; primes[0] = 2U; primes[1] = 3U; printf("2\n3\n"); for (int i=2; i<qty; i++) { int j = primes[i-1]; iter: j += 2U; unsigned bound = (unsigned) sqrt((double) j); for (int k=1; k<i; k++) { if (primes[k] > bound) break; /*Not a viable shortcut for small quantities*/ if (!(j % primes[k])) goto iter; } primes[i] = j; printf("%u\n", j); } return 0; }