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 · 2/6

How it works

This chapter traces each algorithm on small numbers. Following the tables by hand is the fastest way to see why the code looks the way it does.

Euclidean algorithm: gcd(252, 105)

Let r be the remainder of a divided by b. Because r = a - q × b, every common divisor of a and b also divides r, and vice versa. So replacing (a, b) with (b, r) keeps the GCD unchanged while the numbers keep shrinking.

Stepaba mod b
125210542
21054221
342210

The remainder hits 0 at step 3, so the answer is the b of that row: 21. Three steps in total.

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

print(gcd(252, 105))  # 21

Extended Euclid: 240x + 46y = gcd(240, 46)

The extended version tracks, next to each remainder r, the coefficients x and y that express it as 240 × x + 46 × y. Every time a quotient q is produced, all three values follow the same rule: new = previous - q × current.

qrxy
-24010
-4601
5101-5
46-421
145-26
12-947
2023-120

The answer is the row just before the remainder becomes 0: gcd = 2, x = -9, y = 47, and indeed 240 × (-9) + 46 × 47 = -2160 + 2162 = 2. Check that 240 × x + 46 × y = r holds on every row. That invariant is exactly why the algorithm is correct.

def extended_gcd(a: int, b: int) -> tuple[int, int, int]:
    old_r, r = a, b
    old_x, x = 1, 0
    old_y, y = 0, 1
    while r:
        q = old_r // r
        old_r, r = r, old_r - q * r
        old_x, x = x, old_x - q * x
        old_y, y = y, old_y - q * y
    return old_r, old_x, old_y

print(extended_gcd(240, 46))  # (2, -9, 47)

Fast exponentiation: 3^13 mod 7

Instead of twelve multiplications, look at the exponent in binary. 13 = 1101 (base 2) = 8 + 4 + 1, so 3^13 = 3^8 × 3^4 × 3^1. Keep squaring the base (3, 3^2, 3^4, 3^8, …) and multiply it into the result only where the exponent has a 1 bit.

exp (binary)lowest bitresultbase (for next step)
110111 × 3 = 33^2 = 9 ≡ 2
110032^2 = 4
1113 × 4 = 12 ≡ 54^2 = 16 ≡ 2
115 × 2 = 10 ≡ 32^2 = 4

The answer is 3. Fermat's little theorem confirms it: 3^6 ≡ 1 (mod 7), so 3^13 = (3^6)^2 × 3 ≡ 3. The number of multiplications is proportional to the number of bits in the exponent, so even an exponent of 10^18 needs only about 60 iterations.

Sieve of Eratosthenes: primes up to 30

Walk upward from 2. Whenever you meet a number that has not been crossed out, it is prime, and you cross out all of its multiples. It is enough to start at i × i: any smaller multiple i × k with k < i was already crossed out while processing the smaller factor k.

inewly crossed out
24, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
39, 15, 21, 27 (12, 18, 24 and 30 are already gone)
4already crossed out, skip
525 (30 is already gone)
66 × 6 = 36 exceeds 30, stop

What remains is 2, 3, 5, 7, 11, 13, 17, 19, 23, 29: ten primes. The outer loop only runs while i × i ≤ n, so for 30 the work is effectively done at i = 5.

Factorization and nCr mod p

The simplest factorization method is trial division up to √n. For 360, divide by 2 three times (360, 180, 90, 45), then by 3 twice (45, 15, 5). The leftover 5 has no divisor up to √5, so it is prime, and 360 = 2^3 × 3^2 × 5.

A binomial coefficient C(n, r) = n! / (r! × (n - r)!) modulo a prime p cannot be computed by plain division. Instead you multiply by the inverse of the denominator. Inverting with Fermat's little theorem gives C(n, r) ≡ n! × (r!)^(p-2) × ((n-r)!)^(p-2) (mod p) when n < p.

p = 10**9 + 7

def ncr_mod(n: int, r: int) -> int:
    if r < 0 or r > n:
        return 0
    num = den = 1
    for i in range(r):
        num = num * (n - i) % p
        den = den * (i + 1) % p
    return num * pow(den, p - 2, p) % p

print(ncr_mod(10, 3))          # 120
print(ncr_mod(100000, 50000))  # 149033233 — the exact value has over 30,000 digits

Summary

The Euclidean algorithm shrinks big numbers by replacing them with remainders, and the extended version carries the Bezout coefficients along. Fast exponentiation uses the binary form of the exponent to cut the number of multiplications to a logarithm. The sieve crosses out multiples starting at i × i to find every prime in a range at once, and nCr mod p multiplies by inverses instead of dividing. The next chapter turns all of this into reusable code.

Questions about this chapter?
Previous chapterConceptsNext chapterImplementation

0 comments

Top commentsNewest first

Sign in · Sign in to leave a comment.