Menu
Coddy logo textTech

Euclidean algorithm

Lesson 11 of 20 in Coddy's Mathematical Riddles course.

A more efficient method is the Euclidean algorithm, a variant in which the difference of the two numbers x and y is replaced by the remainder of the division of y by x.

Denoting this remainder as y mod x, the algorithm replaces (x, y) by (x, y mod x) repeatedly until the pair is (0, d), where d is the greatest common divisor.

challenge icon

Challenge

Medium

Write python code, gcd2, that calculates GCD, based Euclidean algorithm, that get a vector v with two given numbers.

How faster is this code compering to Euclid's algorithm?

Try it yourself

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include "solution.h"

int main() {
    int v[4096];
    int vn = 0;
    char line[65536];
    if (!fgets(line, sizeof(line), stdin)) line[0] = '\0';
    char* tok = strtok(line, " \t\r\n");
    while (tok) { v[vn++] = atoi(tok); tok = strtok(NULL, " \t\r\n"); }
    int r = gcd2(v, vn);
    printf("%d\n", r);
    return 0;
}

All lessons in Mathematical Riddles

6Greatest common divisor

IntroductionEuclidean algorithmPhi function

9Binary numbers

Introduction