Simplify Your Workflow: Search MiniWebtool.
Add Extension
Home Page > Math > Advanced Math Operations > Modular Exponentiation Calculator

Modular Exponentiation Calculator

Calculate modular exponentiation a^b mod n efficiently using the binary exponentiation (fast power) algorithm. Enter the base, exponent, and modulus to get instant results with a step-by-step breakdown of the squaring-and-multiply method, binary decomposition visualization, and cryptographic context.

Modular Exponentiation Calculator
Examples:
COMPUTING
ab mod n
^
mod

Embed Modular Exponentiation Calculator Widget

About Modular Exponentiation Calculator

The Modular Exponentiation Calculator computes \(a^b \bmod n\) — raising a base \(a\) to an exponent \(b\) and taking the remainder when divided by modulus \(n\). It uses the binary exponentiation algorithm (also called fast power or exponentiation by squaring), which reduces the operation from \(O(b)\) multiplications to just \(O(\log b)\). This is the same algorithm used in real-world cryptographic implementations like RSA, Diffie-Hellman, and ElGamal.

Applications of Modular Exponentiation

🔐
RSA Encryption
Encrypt and decrypt messages using modular exponentiation with large prime products
🤝
Diffie-Hellman
Key exchange protocol computing g^a mod p for secure shared secrets
Digital Signatures
DSA, ECDSA, and EdDSA all rely on modular exponentiation
🧪
Primality Testing
Fermat and Miller-Rabin tests use a^(n-1) mod n to check primality
🏆
Competitive Programming
Modular arithmetic with fast power is essential for contest problems
🔗
Blockchain
Proof-of-work and cryptographic hashing rely on modular arithmetic

How the Binary Exponentiation Algorithm Works

The key insight is that we can decompose any exponent into a sum of powers of 2 using its binary representation. For example, \(b = 13 = 1101_2 = 2^3 + 2^2 + 2^0\), so \(a^{13} = a^{8} \times a^{4} \times a^{1}\).

The algorithm processes the binary digits of the exponent from left to right:

Step 1: Convert the exponent \(b\) to binary.
Step 2: Initialize result = 1 (or = base if first bit is 1).
Step 3: For each subsequent bit: Square the result (mod n). If the bit is 1, also multiply by the base (mod n).
Step 4: After all bits are processed, the result is \(a^b \bmod n\).

Pseudocode

function modpow(base, exp, mod):
    result = 1
    base = base mod mod
    while exp > 0:
        if exp is odd:        // bit is 1
            result = (result × base) mod mod
        exp = exp >> 1        // shift right (divide by 2)
        base = (base × base) mod mod
    return result

Key Formulas

PropertyFormulaDescription
Modular Exponentiation\(a^b \bmod n\)Remainder of a^b divided by n
Fermat's Little Theorem\(a^{p-1} \equiv 1 \pmod{p}\)For prime p and gcd(a,p)=1
Euler's Theorem\(a^{\phi(n)} \equiv 1 \pmod{n}\)For gcd(a,n)=1, where φ is Euler's totient
Binary Method Complexity\(O(\log b)\) multiplicationsAt most 2·log₂(b) modular multiplications
RSA Encryption\(c = m^e \bmod n\)Encrypt message m with public key (e, n)
RSA Decryption\(m = c^d \bmod n\)Decrypt ciphertext c with private key d

How to Use the Modular Exponentiation Calculator

  1. Enter the base (a): This is the number you want to raise to a power. It can be positive or negative. For example, enter 7 for computing 7^256 mod 13.
  2. Enter the exponent (b): This must be a non-negative integer. It represents the power. For cryptographic applications, this can be very large (the calculator supports up to 10^18).
  3. Enter the modulus (n): This must be a positive integer. It is the number you divide by to get the remainder. In RSA, this is typically the product of two large primes.
  4. Click Calculate: The calculator computes a^b mod n using binary exponentiation and shows the result instantly.
  5. Watch the animation: Press Play to watch the binary exponentiation algorithm execute step by step. Each bit of the exponent is processed in sequence, showing whether the algorithm squares, or squares and multiplies.
  6. Review the trace: The step-by-step table shows every intermediate computation, and the efficiency comparison shows how much faster binary exponentiation is versus naive repeated multiplication.

Why Binary Exponentiation is Fast

Consider computing \(2^{1000} \bmod 13\). The naive approach requires 999 multiplications. Binary exponentiation converts 1000 to binary (1111101000), which has 10 bits. It needs at most 9 squarings plus a few multiplies for each '1' bit — roughly 15 operations total. That is about 98.5% fewer operations. For cryptographic-scale exponents with hundreds of digits, the difference is astronomical: binary method takes thousands of operations where naive would require more operations than atoms in the universe.

FAQ

What is modular exponentiation?
Modular exponentiation computes (a^b) mod n — it raises a base to an exponent, then takes the remainder when divided by a modulus. It is the core operation in public-key cryptography (RSA, Diffie-Hellman, ElGamal) and is used extensively in number theory, competitive programming, and computer science. The binary exponentiation method computes this efficiently in O(log b) multiplications.
How does binary exponentiation (exponentiation by squaring) work?
Binary exponentiation converts the exponent to its binary representation, then processes each bit from left to right (or right to left). For each bit, it squares the current result modulo n. If the bit is 1, it additionally multiplies the result by the base modulo n. This reduces the number of multiplications from b−1 (naive method) to at most 2×log₂(b), making it feasible to compute with enormous exponents.
Why is modular exponentiation important in cryptography?
RSA encryption computes c = m^e mod n for encryption and m = c^d mod n for decryption, where n is a product of two large primes and the exponents can be hundreds of digits long. Without fast modular exponentiation, these operations would be computationally impossible. The security relies on the fact that the reverse operation (computing the discrete logarithm) is believed to be computationally infeasible.
Can the base be negative?
Yes, negative bases are fully supported. The calculator first reduces the base modulo n (using Python's modular arithmetic, which always returns a non-negative result for positive n). For example, (−3)^2 mod 7 = 9 mod 7 = 2. Negative results never occur because the modular reduction always produces a value in the range [0, n−1].
What happens when the modulus is 1?
Any integer modulo 1 equals 0. This is because dividing any integer by 1 gives the integer itself with a remainder of 0. So a^b mod 1 = 0 for all values of a and b. The calculator handles this as a special case.

Reference this content, page, or tool as:

"Modular Exponentiation Calculator" at https://MiniWebtool.com/modular-exponentiation-calculator/ from MiniWebtool, https://MiniWebtool.com/

by miniwebtool team. Updated: 2026-04-16

You can also try our AI Math Solver GPT to solve your math problems through natural language question and answer.

Related MiniWebtools:

Advanced Math Operations:

Top & Updated:

Random PickerRandom Name PickerBatting Average CalculatorLine CounterRelative Standard Deviation CalculatorFPS ConverterSort NumbersERA CalculatorMAC Address GeneratorRemove SpacesInstagram User ID LookupWord to Phone Number ConverterFacebook User ID LookupMAC Address LookupSum CalculatorFeet and Inches to Cm ConverterOPS CalculatorRandom Quote GeneratorRandom Truth or Dare GeneratorSHA256 Hash GeneratorPercent Off CalculatorBitwise CalculatorSquare Root (√) CalculatorVertical Jump CalculatorSalary Conversion CalculatorLog Base 10 CalculatorRoman Numerals ConverterNumber of Digits CalculatorSlope and Grade CalculatorOn Base Percentage CalculatorAudio SplitterSlugging Percentage CalculatorMP3 LooperSaturn Return CalculatorDoubling Time CalculatorPhone Number ExtractorCaffeine Overdose CalculatorJob FinderRandom IMEI GeneratorOne Rep Max (1RM) CalculatorMerge VideosClothing Size ConverterSun, Moon & Rising Sign Calculator 🌞🌙✨First n Digits of PiNumber to Word ConverterCompare Two StringsCompound Growth CalculatorAI Text HumanizerCm to Feet and Inches ConverterRandom Poker Hand GeneratorBinary to Gray Code ConverterRandom Birthday GeneratorDecimal to BCD ConverterRandom Fake Address GeneratorBCD to Decimal ConverterRandom Superpower GeneratorRandom Activity GeneratorWAR CalculatorOctal CalculatorAdd Prefix and Suffix to TextWHIP CalculatorGrade CalculatorRandom Movie PickerFile Size ConverterImage ResizerRandom Writing Prompt GeneratorVideo to Image ExtractorTime Duration CalculatorYouTube Channel StatisticsPercent Growth Rate CalculatorLove Compatibility CalculatorText FormatterQuotient and Remainder CalculatorRemove AccentDay of Year CalendarStair CalculatorCM to Inches ConverterInvisible Text GeneratorList of Prime NumbersRandom Loadout GeneratorOutlier CalculatorAdd Text to ImageArc Length CalculatorLeap Years ListRemove Leading Trailing SpacesSHA512 Hash GeneratorRandom Emoji GeneratorRandom Object GeneratorVideo CropperRandom Chess Opening GeneratorWord Ladder GeneratorGray Code to Binary ConverterConnect the Dots GeneratorRandom Number PickerNumber ExtractorImage CompressorAI ParaphraserCryptogram GeneratorRandom Group GeneratorEmail ExtractorURL ExtractorAI Punctuation AdderDay of the Year Calculator - What Day of the Year Is It Today?Video CompressorBinary to BCD ConverterIP Address to Hex ConverterSort Lines AlphabeticallyHex to BCD ConverterBCD to Binary ConverterLottery Number GeneratorBCD to Hex ConverterMedian CalculatorStandard Error CalculatorList RandomizerBreak Line by CharactersAverage CalculatorModulo CalculatorPVIFA CalculatorReverse VideoHypotenuse CalculatorRemove Audio from VideoActual Cash Value CalculatorScientific Notation to Decimal ConverterAngel Number CalculatorLog Base 2 CalculatorRoot Mean Square CalculatorSum of Positive Integers CalculatorSHA3-256 Hash GeneratorAI Sentence Expander📅 Date CalculatorLbs to Kg ConverterHex to Decimal ConverterConvolution CalculatorMAC Address AnalyzerRandom String GeneratorAmortization CalculatorMarkup CalculatorPVIF CalculatorName Number CalculatorDecimal to Hex ConverterInstagram Font GeneratorSocial Media Image Size GuideTikTok Money CalculatorTwitter/X Character CounterTwitter/X Timestamp ConverterYouTube Watch Time CalculatorTwitch Earnings CalculatorYouTube Shorts Monetization CalculatorFacebook Ad Cost CalculatorSocial Media ROI CalculatorSocial Media Post Time OptimizerSocial Media Username CheckerCTR CalculatorROAS CalculatorInfluencer ROI CalculatorForce CalculatorAcceleration CalculatorVelocity CalculatorMomentum CalculatorProjectile Motion CalculatorKinetic Energy CalculatorPotential Energy CalculatorWork and Power CalculatorDensity CalculatorPressure CalculatorIdeal Gas Law CalculatorFree Fall CalculatorTorque CalculatorHorsepower CalculatorDilution CalculatorChemical Equation BalancerStoichiometry CalculatorPercent Yield CalculatorEmpirical Formula CalculatorBoiling Point CalculatorTitration CalculatorMole/Gram/Particle ConverterIrregular Polygon Area CalculatorFrustum CalculatorTorus Calculator3D Distance CalculatorGreat Circle Distance CalculatorCircumscribed Circle (Circumcircle) CalculatorInscribed Circle (Incircle) CalculatorAngle Bisector CalculatorTangent Line to Circle CalculatorHeron's Formula CalculatorCoordinate Geometry Distance CalculatorVolume of Revolution CalculatorSurface of Revolution CalculatorParametric Curve GrapherRiemann Sum CalculatorTrapezoidal Rule CalculatorSimpson's Rule CalculatorImproper Integral CalculatorL'Hôpital's Rule CalculatorMaclaurin Series CalculatorPower Series CalculatorSeries Convergence Test CalculatorInfinite Series Sum CalculatorAverage Rate of Change CalculatorInstantaneous Rate of Change CalculatorRelated Rates SolverOptimization Calculator (Calculus)Gradient Calculator (Multivariable)Divergence CalculatorCurl CalculatorLine Integral CalculatorSurface Integral CalculatorJacobian Matrix CalculatorNewton's Method CalculatorRREF Calculator (Row Echelon Form)Matrix Inverse CalculatorMatrix Multiplication CalculatorDot Product CalculatorCross Product CalculatorVector Magnitude CalculatorUnit Vector CalculatorAngle Between Vectors CalculatorNull Space CalculatorColumn Space CalculatorCramer's Rule CalculatorMatrix Diagonalization CalculatorQR Decomposition CalculatorCholesky Decomposition CalculatorMatrix Power CalculatorCharacteristic Polynomial CalculatorBayes' Theorem CalculatorF-Test / F-Distribution CalculatorHypergeometric Distribution CalculatorNegative Binomial Distribution CalculatorGeometric Distribution CalculatorExponential Distribution CalculatorWeibull Distribution CalculatorBeta Distribution CalculatorSpearman Rank Correlation CalculatorFisher's Exact Test CalculatorContingency Table CalculatorOdds Ratio CalculatorRelative Risk CalculatorEffect Size CalculatorPermutations with Repetition CalculatorModular Exponentiation CalculatorPrimitive Root CalculatorPerfect Number CheckerAmicable Number CheckerTwin Prime FinderMersenne Prime CheckerGoldbach Conjecture VerifierMöbius Function CalculatorEgyptian Fraction CalculatorFibonacci Number CheckerDigital Root CalculatorPartition Function CalculatorBoolean Algebra SimplifierKarnaugh Map (K-Map) SolverLogic Gate SimulatorGraph Coloring CalculatorTopological Sort CalculatorAdjacency Matrix CalculatorRecurrence Relation SolverInclusion-Exclusion CalculatorLinear Programming SolverTraveling Salesman Solver (TSP)Hamiltonian Path CheckerPlanar Graph CheckerNetwork Flow Calculator (Max Flow)Stable Marriage Problem SolverFirst-Order ODE SolverSecond-Order ODE SolverDirection Field / Slope Field PlotterEuler's Method CalculatorBernoulli ODE SolverSystem of ODEs SolverGroup Theory Order CalculatorRing and Field CalculatorJordan Normal Form CalculatorMatrix Exponential CalculatorTensor Product CalculatorFast Fourier Transform (FFT) CalculatorZ-Transform CalculatorNumerical Integration CalculatorTOML to JSON ConverterJSON to CSV ConverterXML to JSON ConverterSQL to MongoDB Query ConverterCSS Flexbox PlaygroundCSS Grid GeneratorJWT GeneratorBcrypt Hash Generator / CheckerColor Code Converter (All Formats)Git Command Generator.env File GeneratorLorem Picsum / Placeholder Image GeneratorText to Binary/Hex/ASCII ConverterSyllable CounterSentence CounterParagraph CounterSpeaking Time CalculatorReading Time CalculatorWhitespace VisualizerStrikethrough Text GeneratorTorque Converter (Nm, ft-lb, kgf-cm)Data Transfer Rate ConverterFuel Efficiency ConverterAstronomical Unit ConverterRing Size ConverterPaper Size ReferenceGas Mileage CalculatorEV Range CalculatorEV Charging Time Calculator0–60 / Quarter Mile CalculatorCar Lease CalculatorVehicle Towing Capacity CalculatorExposure Triangle CalculatorCrop Factor CalculatorMegapixel to Print Size CalculatorPhoto File Size EstimatorMusic BPM TapperMusic Key TransposerVideo Bitrate CalculatorSeed Germination Rate CalculatorFertilizer Calculator (NPK)Raised Bed Soil CalculatorFrost Date CalculatorLawn Fertilizer CalculatorCompost Calculator (C:N Ratio)Solar Panel CalculatorSolar ROI CalculatorHome Energy Audit CalculatorAppliance Energy Cost CalculatorWater Usage CalculatorElectricity Generation Cost CalculatorHeat Loss CalculatorFlight Distance CalculatorTravel Budget CalculatorJet Lag CalculatorPacking List GeneratorTip Splitter (Advanced)Lease vs Buy CalculatorHourly Rate Calculator (Freelancer)Invoice Late Fee CalculatorESPP CalculatorStock Split CalculatorOptions Probability CalculatorDollar to Gold ConverterBeam Load CalculatorPipe Flow CalculatorBolt Torque CalculatorSteel Weight CalculatorGravel, Sand & Topsoil Calculator