jpp/zad2/iter/module.adb
2024-03-22 11:43:36 +01:00

95 lines
2.1 KiB
Ada

with Ada.Strings; use Ada.Strings;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
package body Module is
function factorial(n : Natural) return Natural is
result : Natural := 1;
begin
for i in 1 .. n loop
result := result * i;
end loop;
return result;
end factorial;
function gcd(a : Natural; b : Natural) return Natural is
r : Natural;
aa : Natural := a;
bb : Natural := b;
begin
if a = 0 then
return b;
end if;
while bb > 0 loop
r := aa mod bb;
aa := bb;
bb := r;
end loop;
return aa;
end gcd;
function gcdExtended(a : Integer; b : Integer; x : out Integer; y : out Integer) return Integer is
x1 : Integer := 0;
y1 : Integer := 1;
q : Integer;
tempX, tempY, tempB : Integer;
aa : Integer := a;
bb : Integer := b;
begin
x := 1;
y := 0;
while bb /= 0 loop
q := aa / bb;
tempX := x - q * x1;
tempY := y - q * y1;
x := x1;
y := y1;
x1 := tempX;
y1 := tempY;
tempB := aa - q * bb;
aa := bb;
bb := tempB;
end loop;
return aa;
end gcdExtended;
function diophantine(a : Integer; b : Integer; c : Integer) return Result is
r : Result;
x0 : Integer := 0;
y0 : Integer := 0;
g : Integer := gcdExtended(abs a, abs b, x0, y0);
begin
r.n := 0;
r.m := 0;
r.resultExists := False;
if a = 0 and b = 0 then
return r;
end if;
if (c rem g) /= 0 then
return r;
end if;
x0 := x0 * (c / g);
y0 := y0 * (c / g);
if a < 0 then
x0 := -x0;
end if;
if b < 0 then
y0 := -y0;
end if;
r.n := x0;
r.m := y0;
r.resultExists := True;
return r;
end diophantine;
end Module;