Cod sursa(job #3231039)

Utilizator IordachescuVladAlexandruIordachescu Vlad-Alexandru IordachescuVladAlexandru Data 23 mai 2024 23:38:12
Problema Algoritmul lui Euclid extins Scor 100
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <stdio.h>
#include <stdlib.h>

#define FILE_IN "euclid3.in"
#define FILE_OUT "euclid3.out"

// pb Algoritmul lui Euclid extins de pe infoarena

// ecuatie: ax + by = c

// teorie, tb implementata

typedef struct
{
  int x, y, d;
} EUCLID;

EUCLID eucl_ext ( int a, int b )
{
  EUCLID rez;

  if ( b == 0 )
    {
      rez.d = a, rez.x = 1, rez.y = 0;
      return rez;
    }

  EUCLID aux = eucl_ext ( b, a % b );

  rez.d = aux.d;
  rez.x = aux.y;
  rez.y = aux.x - aux.y * ( a / b );

  return rez;
}

int main ( void )
{
  FILE *fin, *fout;
  fin = fopen ( FILE_IN, "r" );
  fout = fopen ( FILE_OUT, "w" );
  if ( fin == NULL || fout == NULL )
    {
      perror ( "Eroare la deschidere fisiere\n" );
      exit ( -1 );
    }

  EUCLID rez;
  int t, a, b, c;

  fscanf ( fin, "%d\n", &t );

  for ( int query = 0; query < t; query++ )
    {
      fscanf ( fin, "%d %d %d\n", &a, &b, &c );
      rez = eucl_ext ( a, b );
      if ( c % rez.d == 0 )
	{
	  int x = rez.x * ( c / rez.d );
	  int y = rez.y * ( c / rez.d );
	  fprintf ( fout, "%d %d\n", x, y );
	  printf ( "%d %d\n", x, y );
	}
      else
	{
	  fprintf ( fout, "0 0\n" ); // Nu există soluție
	  printf ( "0 0\n" ); // Nu există soluție
	}
    }

  if ( ( fclose ( fin ) ) != 0 || ( fclose ( fout ) ) != 0 )
    {
      perror ( "Eroare la inchidere fisiere\n" );
      exit ( -2 );
    }

  return 0;
}