Cod sursa(job #1246979)

Utilizator cristid9Cristi D cristid9 Data 21 octombrie 2014 21:50:24
Problema Algoritmul lui Euclid Scor 50
Compilator c Status done
Runda Arhiva educationala Marime 1.2 kb
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define PAIRS 100000

// Returns the great common devisor of the numbers passed as arguments.
unsigned int gcd(unsigned int a, unsigned int b)
{
    while(a != 0 && b != 0 ) {
        if(fmax(a, b) == a) {
            a = a - b;
        }
        else {
            b = b - a;
        }
    }

    return fmax(a, b);
}

void getNumberPairs(FILE *fileHandle, int values[][2])
{
    char *linePtr = NULL;
    size_t len = 0;
    ssize_t read;
    
    for(int i = 0; (read = getline(&linePtr, &len, fileHandle)) != -1; i++) {
        fscanf(fileHandle, "%d %d", &values[i][0], &values[i][1]);
    }
    free(linePtr);
}

int main()
{
    FILE *fileHandleIn = fopen("euclid2.in", "r");
    FILE *fileHandleOut = fopen("euclid2.out", "w");

    // get the number of pairs
    int pairs;
    int values[PAIRS][2]; 
    fscanf(fileHandleIn, "%d", &pairs);
   
    // get the pairs
    getNumberPairs(fileHandleIn, values);

    // test the correctness of pairs
    for(int i = 0; i < pairs; i++) {
        fprintf(fileHandleOut, "%u\n", gcd(values[i][0], values[i][1]));
    }
    
    fclose(fileHandleIn);
    fclose(fileHandleOut);

    return 0;
}