Skip to main content
Join the official 2019 Python Developers SurveyStart the survey!

Modular arithmetic in Python

Project description

Build Status Documentation Status

Description

Modular arithmetic is arithmetic for integers, where numbers wrap around when reaching a given value called modulus. For example 6 ≡ 1 (mod 5). Modular arithmetic has several practical applications including: music, banking, book publishing, cryptography… and of course math.

The purpose of this package is to simplify the use of modular arithmetic in Python3.

Usage

This package provides Mod integers that compute arithmetic operations like + - * // ** with a modulus:

from mod import Mod

# Funny math here

x = Mod(5, 7)      # x ≡ 5 (mod 7)

(x + 2) == 0       # True: 5 + 2 ≡ 7 ≡ 0 (mod 7)
(x + 7) == x       # True: 5 + 7 ≡ 12 ≡ 5 (mod 7)
(x**3) == (x + 1)  # True: 5³ ≡ 125 ≡ 6 (mod 7)
(1 // x) == 3      # True: 5 × 3 ≡ 15 ≡ 1 (mod 7) ⇒ 5⁻¹ ≡ 3 (mod 7)

A naive implementation of RSA encryption algorithm using mod package:

from mod import Mod


# My RSA keys
public_key = Mod(3, 61423)
private_key = Mod(40619, 61423)

# My very secret message
top_secret_message = 666

# RSA encryption
encrypted = top_secret_message**public_key

# RSA decryption
decrypted = encrypted**private_key

# My secret message have been correctly encrypted and decrypted :-)
assert decrypted == top_secret_message

Note

  • Mod is based on integer modulo operation %, not math.fmod
  • the result of an operation between a Mod and an int is a Mod
  • the result of an operation between a Mod and a float is a float

Package documentation: mod.Mod

Install

Run the following command to install mod package

pip3 install mod

Indices

mod — Copyright (c) 2017 Y. SOMDA, MIT License

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for mod, version 0.2.4
Filename, size File type Python version Upload date Hashes
Filename, size mod-0.2.4-py3-none-any.whl (4.0 kB) File type Wheel Python version py3 Upload date Hashes View hashes
Filename, size mod-0.2.4.tar.gz (4.3 kB) File type Source Python version None Upload date Hashes View hashes

Supported by

Elastic Elastic Search Pingdom Pingdom Monitoring Google Google BigQuery Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN SignalFx SignalFx Supporter DigiCert DigiCert EV certificate StatusPage StatusPage Status page