Skip to main content
ProductsDesktop toolsTASTECADDrawing reviewTASTEFILESFile managementTASTEFTPFile transferTASTESSHRemote workspaceTASTEZIPCompression and extractionTASTEWINMFile managementDeveloper toolsTASTECODERust integrated development environmentTASTESTUDIOIntegrated development and test environmentTASTEETLData integration (ETL)ServersTASTEREMOTERemote desktop serverTASTEGEOGeospatial serverTASTEMAILMail workspaceInvestingTASTESTOCKStock auto-trading desktop appGet startedDownloadsDocumentationBuyAll products
Marketplace
News
TechNewsToday's dev newsDeveloper docsProgramming languagesRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWeb front-end frameworksNext.jsReactVue.js · NuxtSvelteKitAngularServer frameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressApp & desktop frameworksTauriFlutterReact NativeElectronAlgorithmsAlgorithm basicsCore algorithmsAdvanced algorithmsPractical algorithms
CommunityProjectsDevelopment logsPromptsAI tool issuesShowcaseCommunity guide
Work with usTech transferWebsite buildDesktop app buildRelease and payment pipelineSales partnerContact
ServicesRemote desktopCustom installer packages
TASTEDEV
Products

Desktop tools

TASTECADComplex drawings, opened with easeTASTEFILESJust the files you need, as fast as possibleTASTEFTPThe tidiest path for your filesTASTESSHA stronger link between you and your serversTASTEZIPPack faster, unpack saferTASTEWINMA keyboard-first file manager with two panes

Developer tools

TASTECODEEdit, build, debug and test Rust apps in one windowTASTESTUDIOFrom editing to remote tests and approved AI fixesTASTEETLMove data while you watch the values

Servers

TASTEREMOTEA remote desktop you run on your own serverTASTEGEORebuilding a GeoServer-compatible geospatial server in RustTASTEMAILTake back control of your email

Investing

TASTESTOCKStock auto-trading that follows the rules you set: when, and what

Get started

DownloadsLatest builds of every productDocsHow to use each productBuySubscriptions and perpetual licencesAll productsEvery product at a glance
All products
MarketplaceNews
Tech

News

Today's dev newsOfficial announcements on languages, frameworks, GitHub and AIDeveloper docsGuides to languages, frameworks and algorithms

Programming languages

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Web front-end frameworksNext.jsReactVue.js · NuxtSvelteKitAngular
Server frameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
App & desktop frameworksTauriFlutterReact NativeElectron

Algorithms

Algorithm basicsComplexity analysis · Sorting · Searching · Basic data structures · Trees and heapsCore algorithmsGraph traversal · Shortest paths & minimum spanning trees · Dynamic programming · Greedy algorithms · Divide and conquer · BacktrackingAdvanced algorithmsString algorithms · Math and number theory · Bit manipulation · Segment trees · Union-findPractical algorithmsCoding interview strategy · LRU cache · Rate limiting · Consistent hashing
All development docs
Community
ProjectsDiscover builders and their workDevelopment logsDecisions and lessons learnedPromptsReusable instructionsAI tool issuesProblems and workarounds for Claude, Codex, GeminiShowcaseFinished resultsCommunity guideHow we build in the open
Work with us
Tech transferNative apps in Rust and eguiWebsite build10 languages, accounts, docs and downloadsDesktop app buildRust and egui, no WebViewRelease and payment pipelineSigning, MSI, deb, rpm, AppImage, hashesSales partnerRecommend us and earn 30%ContactBuilds, partnerships and investment
Services
Remote desktopReach your computer from a browserCustom installer packagesOnly the features you need, settings preloaded
Buy
EN
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Log in
Log in
TASTEDEV

From small tools to better development.

support@tastedev.netSupport TASTEDEV
ProductsProduct lineupBuyDocsDownloadsMarketplaceSupport
CommunityProjectsDevelopment logsPromptsAI tool issuesShowcase
PoliciesAbout usPrivacy policyTerms of serviceSubscription termsRefund policyCommunity guidelines
AccountLog inSign up
Visitors
Today
Yesterday
Total views
Company
GXSOFT
Representative
CHOI YOUNG GU
Business registration number
853-44-00368
Address
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Phone
+82-10-4404-1523
Email
whitecalvin@tastedev.net
Privacy officer
CHOI YOUNG GU

© 2026 TASTEDEVProduct information is based on verified development sources.Released · improving

Developer docs
Math and number theory
Math and number theoryReference implementationStep-by-step guideOfficial docs and resourcesDiscussionsComments

Other algorithms

Algorithm basics5
Complexity analysisSortingSearchingBasic data structuresTrees and heaps
Core algorithms6
Graph traversalShortest paths & minimum spanning treesDynamic programmingGreedy algorithmsDivide and conquerBacktracking
Advanced algorithms4
String algorithmsBit manipulationSegment treesUnion-find
Practical algorithms4
Coding interview strategyLRU cacheRate limitingConsistent hashing

Algorithm

Math and number theory

GCD and LCM, modular arithmetic and inverses, fast exponentiation, the sieve of Eratosthenes and nCr mod p: the number theory toolkit for algorithms.

Start the guideDiscussions

Number theory studies integers, especially division and remainders. In algorithms it means computing GCDs and LCMs with the Euclidean algorithm, working with huge values through modular arithmetic, and finding modular inverses with the extended Euclidean algorithm or Fermat's little theorem. Fast exponentiation, the sieve of Eratosthenes, prime factorization and binomial coefficients modulo a prime complete the toolkit.

These tools show up constantly in coding interviews and contests as "print the answer modulo 10^9 + 7", and in production they underpin public-key cryptography such as RSA and Diffie-Hellman, hash functions, random number generators and check digits. Most of them run in logarithmic or near-linear time, so knowing how they work turns computations that would never finish into ones that take milliseconds.

Start by tracing the rules of modular arithmetic and the Euclidean algorithm by hand, then implement fast exponentiation and the sieve yourself. Move on to modular inverses and nCr mod p, and if you write C++ or Java, practice handling multiplication overflow and negative remainders. Learn the standard helpers too, such as Python's pow(a, e, m) and math.gcd.

On this page

  1. Highlights
  2. Where it is used
  3. Reference implementation
  4. Step-by-step guide
  5. Official docs and resources
  6. Discussions
  7. Comments

Highlights

Euclidean algorithm

Repeating gcd(a, b) = gcd(b, a mod b) finds the GCD in O(log n); the extended version also returns the coefficients of ax + by = gcd(a, b).

Modular arithmetic and inverses

Addition, subtraction and multiplication preserve remainders, so you reduce after every step; division becomes multiplication by a modular inverse.

Fast exponentiation

Squaring the base over the binary digits of the exponent computes a^e mod m with about log e multiplications instead of e.

Sieve of Eratosthenes

Crossing out multiples of each prime from i × i finds every prime up to n in O(n log log n); a smallest-prime-factor table then factors numbers quickly.

Where it is used

  • Public-key cryptography such as RSA and Diffie-Hellman
  • Hash functions and random number generators
  • Large counting answers modulo 10^9 + 7 in coding interviews
  • Check digits for ISBNs and card numbers

Reference implementation

gcd finds the greatest common divisor with the Euclidean algorithm, and the LCM follows as a // gcd(a, b) * b. mod_pow is fast exponentiation: it walks the bits of the exponent, squaring and multiplying, and with a prime modulus p, a^(p-2) gives the modular inverse of a. sieve uses the sieve of Eratosthenes to list every prime up to 30. Save the file and run python number_theory.py.

number_theory.py

import math


def gcd(a: int, b: int) -> int:
    while b:
        a, b = b, a % b
    return a


def mod_pow(base: int, exp: int, mod: int) -> int:
    result, base = 1 % mod, base % mod
    while exp > 0:
        if exp & 1:
            result = result * base % mod
        base = base * base % mod
        exp >>= 1
    return result


def sieve(n: int) -> list[int]:
    is_prime = [False, False] + [True] * (n - 1)
    for i in range(2, math.isqrt(n) + 1):
        if is_prime[i]:
            for j in range(i * i, n + 1, i):
                is_prime[j] = False
    return [i for i, p in enumerate(is_prime) if p]


MOD = 10**9 + 7
print(gcd(84, 36), 84 // gcd(84, 36) * 36)  # 12 252
print(mod_pow(3, 200, 13))                  # 9
print(mod_pow(3, MOD - 2, MOD))             # 333333336, the inverse of 3
print(sieve(30))                            # [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
python number_theory.py

Step-by-step guide

Six chapters that take you from installation to the core ideas of Math and number theory.

  1. Concepts
  2. How it works
  3. Implementation
  4. Complexity
  5. Practice problems
  6. Real-world use

Official docs and resources

  • OfficialPython math module
  • OfficialPython built-in pow
  • LearnExtended Euclidean Algorithm (cp-algorithms)
  • LearnModular Multiplicative Inverse (cp-algorithms)
  • LearnBinary Exponentiation (cp-algorithms)
  • LearnSieve of Eratosthenes (cp-algorithms)
  • ReferenceEuclidean algorithm (Wikipedia)
  • ReferenceModular arithmetic (Wikipedia)

Discussions

Start a discussion

Ask questions, share experience and trade opinions about Math and number theory.

No discussions yet. Start the first one.

0 comments

Top commentsNewest first

Sign in · Sign in to leave a comment.