Modular arithmetic

Revision as of 21:35, 11 March 2013 by rosettacode>Soegaard (→‎{{header|Racket}}: Removed Racket version)

Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined congruence. This means that two numbers a and b are considered congruent whenever there exists an integer k such that:

Modular arithmetic is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

p is called the congruence modulus. The corresponding set of integers is called the ring, where each element is uniquely represented by the remainder of its euclidean division by p. Addition and multiplication on this ring have the same algebraic structure, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result.

The purpose of this task is to show, if your programming language allows it, how to redefine operators so that they can be used transparently on modular integers. You can do it either by using a dedicated library, or by implementing your own class.

You will use the following function for demonstration:

You will use 13 as the congruence modulus and you will compute f(10).

It is important that the function f is agnostic about whether or not its argument is modular. It should behave the same way with normal and modular integers. In other words, the function is an algebraic expression that could be used with any ring, not just integers.

Perl

There is a CPAN module called Math::ModInt which does the job.

<lang Perl>use Math::ModInt qw(mod); sub f { my $x = shift; $x**100 + $x + 1 }; print f mod(10, 13);</lang>

Output:
mod(1, 13)

Perl 6

There is a Panda module called Modular which works basically as Perl 5's Math::ModInt.

<lang Perl 6>use Modular; sub f(\x) { x**100 + x + 1}; say f( 10 Mod 13 )</lang>

Output:
1 「mod 13」