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

Math and number theory docs
Math and number theory
ConceptsHow it worksImplementationComplexityPractice problemsReal-world use
Discussions

Math and number theory guide · 1/6

Concepts

Number theory studies the properties of integers, above all division and remainders. It turns up in code more often than you might expect: finding when two cycles line up again, reporting a huge count "modulo 10^9 + 7", building a list of primes, or understanding how public-key cryptography such as RSA works. This chapter sets out the vocabulary and intuition used throughout the rest of the guide.

Divisibility and primes

If a divided by b leaves remainder 0, then b is a divisor of a and a is a multiple of b. An integer greater than 1 whose only divisors are 1 and itself is a prime; any other integer greater than 1 is composite. 2, 3, 5, 7 and 11 are prime, while 12 = 2 × 2 × 3 is composite.

The fundamental theorem of arithmetic says every integer greater than 1 can be written as a product of primes in exactly one way, ignoring order. That product is its prime factorization: for example, 360 = 2^3 × 3^2 × 5. Once you know the factorizations, the number of divisors, the GCD and the LCM all fall out of comparing exponents.

GCD and LCM

The greatest common divisor (GCD) is the largest number that divides both inputs; the least common multiple (LCM) is the smallest positive number both inputs divide. For positive a and b, gcd(a, b) × lcm(a, b) = a × b, so a fast GCD gives you the LCM for free.

The standard way to compute a GCD is the Euclidean algorithm. Its key identity is gcd(a, b) = gcd(b, a mod b); when the remainder reaches 0, the current divisor is the answer. The extended Euclidean algorithm additionally finds integers x and y (Bezout coefficients) with a × x + b × y = gcd(a, b). Those coefficients are the key to modular inverses.

import math

print(math.gcd(84, 36))   # 12
print(math.lcm(84, 36))   # 252 (Python 3.9+)
print(84 * 36 // math.gcd(84, 36))  # 252, the same value

Modular arithmetic

a mod m is the remainder when a is divided by m. If a and b leave the same remainder modulo m, we say they are congruent and write a ≡ b (mod m). A clock is the classic example: five hours after 10 o'clock is 3 o'clock, not 15, because 15 ≡ 3 (mod 12).

Modular arithmetic is useful because addition, subtraction and multiplication preserve remainders:

  • (a + b) mod m = ((a mod m) + (b mod m)) mod m
  • (a - b) mod m = ((a mod m) - (b mod m) + m) mod m
  • (a × b) mod m = ((a mod m) × (b mod m)) mod m

So however large the intermediate values would get, you can take the remainder after every step and keep the numbers small. Division does not work this way, though. To compute a / b modulo m you multiply by the modular inverse of b.

MOD = 10**9 + 7

a, b = 123456789, 987654321
print((a * b) % MOD)                  # 259106859
print(((a % MOD) * (b % MOD)) % MOD)  # same value
print(-7 % 3)                         # 2 — Python always returns a non-negative remainder here

Modular inverses and Fermat's little theorem

An x with a × x ≡ 1 (mod m) is the modular inverse of a. It exists only when gcd(a, m) = 1, that is, when a and m are coprime. There are two common ways to find it:

  • Solve a × x + m × y = 1 with the extended Euclidean algorithm; x is the inverse. This works for any modulus.
  • If the modulus is a prime p, Fermat's little theorem gives a^(p-1) ≡ 1 (mod p), so a^(p-2) is the inverse. Compute it with fast exponentiation.

This is why competitive programming loves 10^9 + 7 and 998244353. Both are prime, so every nonzero value has an inverse, and both sit near 2^30, so the product of two residues still fits in a 64-bit integer.

p = 10**9 + 7
inv3 = pow(3, p - 2, p)         # Fermat's little theorem
print(3 * inv3 % p)             # 1
print(pow(3, -1, p) == inv3)    # True — built in since Python 3.8

Vocabulary

TermMeaning
Prime / compositeOnly divisors are 1 and itself / any other integer above 1
GCD / LCMGreatest common divisor / least common multiple
CoprimeTwo numbers with gcd(a, b) = 1
CongruentSame remainder modulo m, a ≡ b (mod m)
Modular inverseThe x with a × x ≡ 1 (mod m)
Fast exponentiationSquare repeatedly over the binary digits of the exponent, O(log e) multiplications
Sieve of EratosthenesFind every prime up to n by crossing out multiples of primes
nCr mod pA binomial coefficient reduced modulo a prime p

When to reach for number theory

  • The statement says "print the answer modulo 10^9 + 7"
  • Cycles, repetition, or events that must coincide (LCM)
  • Splitting into equal parts or reducing a ratio (GCD)
  • Many primality checks or prime counts over a range (sieve)
  • Counting problems whose exact answer is astronomically large (nCr mod p)

Summary

Number theory gives you five core tools: the Euclidean algorithm (GCD and LCM), the rules of modular arithmetic, modular inverses (extended Euclid or Fermat), fast exponentiation, and the sieve of Eratosthenes. The next chapter traces each of them step by step on small inputs.

Questions about this chapter?
Next chapterHow it works

0 comments

Top commentsNewest first

Sign in · Sign in to leave a comment.