aboutsummaryrefslogtreecommitdiff
path: root/templates/zmodn-1.cpp
blob: a8e26caca364be9d9d7abd51cc9c3dcff17ce966 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
#include <optional>
#include <tuple>

std::tuple<int, int, int> extended_gcd(int a, int b) {
	if (b == 0) return {a, 1, 0};
	auto [g, x, y] = extended_gcd(b, a%b);
	return {g, y, x - y*(a/b)};
}

template<int N>
class Zmod {
public:
	int value;

	Zmod(int z) : value{(z%N + N) % N} {}
	int toint() const { return value; }

	Zmod operator+(const Zmod& z) const { return value + z.value; }
	Zmod operator-(const Zmod& z) const { return value - z.value; }
	Zmod operator*(const Zmod& z) const { return value * z.value; }

	std::optional<Zmod> inverse() const {
		auto [g, a, _] = extended_gcd(value, N);
		return g == 1 ? Zmod(a) : std::optional<Zmod>{};
	}

	std::optional<Zmod> operator/(const Zmod& d) const {
		auto i = d.inverse();
		return i ? (*this) * i.value() : i;
	}

	std::optional<Zmod> operator/=(const Zmod& d) {
		auto q = *this / d;
		return q ? (*this = q.value()) : q;
	}
};

int main() {
	Zmod<57> x(34);
	Zmod<57> y(11);

	std::cout << "34 * 11 = " << (x * y).value << " (mod 57)" << std::endl;

	if (auto inv = y.inverse(); inv)
		std::cout << "11 * " << inv.value().value << " = 1 (mod 57)" << std::endl;
	else
		std::cout << "11 is not invertible in Z/57Z" << std::endl;


	// The following line gives a run-time exception
	// Zmod<0> z(157);

	return 0;
}

Generated with cgit - Back to sebastiano.tronto.net