Modular arithmetic: Difference between revisions
Content deleted Content added
Ada version |
Thundergnat (talk | contribs) Rename Perl 6 -> Raku, alphabetize, minor clean-up |
||
Line 138:
<pre>f(ModularInteger(10, 13)) = ModularInteger(1, 13)</pre>
=={{header|C
{{trans|Java}}
<lang csharp>using System;
Line 308 ⟶ 228:
{{out}}
<pre>x ^ 100 + x + 1 for x = ModInt(10, 13) is ModInt(1, 13)</pre>
=={{header|C++}}==
{{trans|D}}
<lang cpp>#include <iostream>
#include <ostream>
template<typename T>
T f(const T& x) {
return (T) pow(x, 100) + x + 1;
}
class ModularInteger {
private:
int value;
int modulus;
void validateOp(const ModularInteger& rhs) const {
if (modulus != rhs.modulus) {
throw std::runtime_error("Left-hand modulus does not match right-hand modulus.");
}
}
public:
ModularInteger(int v, int m) {
modulus = m;
value = v % m;
}
int getValue() const {
return value;
}
int getModulus() const {
return modulus;
}
ModularInteger operator+(const ModularInteger& rhs) const {
validateOp(rhs);
return ModularInteger(value + rhs.value, modulus);
}
ModularInteger operator+(int rhs) const {
return ModularInteger(value + rhs, modulus);
}
ModularInteger operator*(const ModularInteger& rhs) const {
validateOp(rhs);
return ModularInteger(value * rhs.value, modulus);
}
friend std::ostream& operator<<(std::ostream&, const ModularInteger&);
};
std::ostream& operator<<(std::ostream& os, const ModularInteger& self) {
return os << "ModularInteger(" << self.value << ", " << self.modulus << ")";
}
ModularInteger pow(const ModularInteger& lhs, int pow) {
if (pow < 0) {
throw std::runtime_error("Power must not be negative.");
}
ModularInteger base(1, lhs.getModulus());
while (pow-- > 0) {
base = base * lhs;
}
return base;
}
int main() {
using namespace std;
ModularInteger input(10, 13);
auto output = f(input);
cout << "f(" << input << ") = " << output << endl;
return 0;
}</lang>
{{out}}
<pre>f(ModularInteger(10, 13)) = ModularInteger(1, 13)</pre>
=={{header|D}}==
Line 902:
{{out}}
<pre>mod(1, 13)</pre>
=={{header|Phix}}==
Line 1,108 ⟶ 1,100:
(with-modulus 13 (f 10))
;; => 1</lang>
=={{header|Raku}}==
(formerly Perl 6)
There is an ecosystem module called Modular which works basically as Perl 5's Math::ModInt.
<lang perl6>use Modular;
sub f(\x) { x**100 + x + 1};
say f( 10 Mod 13 )</lang>
{{out}}
<pre>1 「mod 13」</pre>
=={{header|Ruby}}==
Line 1,201 ⟶ 1,202:
}</lang>
=={{header|Sidef}}==
{{trans|Ruby}}
|