Never been to DZone Snippets before?

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

About this user

Guildorn Tanaleth

« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS 

Fibonacci function

This function returns the nth Fibonacci number, though most platforms can go no higher than the 47th.
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;
}

Factorial function

A (non-recursive) factorial function
int factorial(int x) {
 int fac = 1;
 for (int i=2; i<=x; i++) fac *= i;
 return fac;
}


Also, with this function defined, you can use two macros for calculating combinations & permutations:
#define nCr(n, r) (factorial(n) / factorial(n-r) / factorial(r))
#define nPr(n, r) (factorial(n) / factorial(n-r))

Modular inverse function

This function calculates & returns the inverse of a modulo n, both of which should be positive. If the inverse does not exist, 0 is returned. If you don't know what this means, don't bother.
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;
}

Greatest Common Denominator function

This function returns the greatest common denominator (GCD) of its arguments.
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;
}

Prime number generator

This program will calculate & list the first n primes, where n is a number specified on the command line or (if none is specified) 100. n is only limited by the size of ints on your platform.
#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;
}
« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS