Modular arithmetic

From Rosetta Code
Revision as of 06:31, 21 February 2013 by Grondilu (talk | contribs) (Created page with "{{draft task}} '''Modular arithmetic''' is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with ...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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.

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:

p is called the congruence modulus. The corresponding set of integers is called the ring. 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).

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**2 + $x + 1 }; print f mod(10, 13);</lang>

Output:
mod(8, 13)