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

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

GCD: Divide et Impera

Calculates the Greatest Common Denominator (GCD) of an array of ints using a Divide at Impera approach.

Time: O(lg(n))
Memory: O(n)

#include <stdio.h>

int gcd(int a, int b) {
	int r = a % b;
	while (r) {
		a = b;
		b = r;
		r = a % b;
	}
	return b;
}

int gcdv(int *v, int p, int r) {
	if (r == p + 1) {
		//printf("%d,%d: %d\n", p, r, gcd(v[p], v[r]));
		return gcd(v[p], v[r]);
	}
	
	if (r == p) {
		//printf("%d: %d\n", r, v[r]);
		return v[p];
	}
	
	int q = (p + r) / 2;
	//printf("%d,%d: %d\n", p, r, gcd(gcdv(v, p, q), gcdv(v, q + 1, r)));
	return gcd(gcdv(v, p, q), gcdv(v, q + 1, r));
}

int main(int argc, char *argv[]) {
	int v[] = {45, 60, 125, 345, 65, 9875, 4555};
	
	printf("GCD: %d\n", gcdv(v, 0, 6));
	
	return 0;
}

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;
}

GCD of two numbers.

// finds GCD of a and b using Euclidian algorithm

public int GCD(int a, int b)
{
   if (b==0) return a;
   return GCD(b,a%b);
}

LCM function

    ; uses GCD function
    lcm: func [
        {Returns the least common multiple of m and n.}
        m [integer!]
        n [integer!]
    ][
        abs either zero? n [0] [(m * n) / gcd m n]
    ]

GCD function

    gcd: func [
        {Returns the greatest common denominator of m and n.}
        m [integer!]
        n [integer!]
    ][
        ;Euclid's algorithm
        abs either zero? n [0] [either zero? (m // n) [n] [gcd n (m // n)]]
    ]
« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS