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 PickerInstagram User ID LookupFPS ConverterLine CounterRelative Standard Deviation CalculatorSort NumbersImage ResizerMAC Address GeneratorBatting Average CalculatorRemove SpacesFacebook User ID LookupERA CalculatorRandom Truth or Dare GeneratorFeet and Inches to Cm ConverterWord to Phone Number ConverterMAC Address LookupSun, Moon & Rising Sign Calculator 🌞🌙✨Slope and Grade CalculatorPercent Off CalculatorSum CalculatorBitwise CalculatorMP3 LooperAudio SplitterInvisible Text GeneratorRandom IMEI GeneratorRoman Numerals ConverterAI Text HumanizerWord Ladder GeneratorRandom Credit Card GeneratorNumber of Digits CalculatorSHA256 Hash GeneratorHalfway Date Calculator📷 OCR / Image to TextLog Base 10 CalculatorRandom Superpower GeneratorVertical Jump CalculatorRandom Quote GeneratorWAR CalculatorMerge VideosRandom Birthday GeneratorCm to Feet and Inches ConverterPhone Number ExtractorMaster Number CalculatorSalary Conversion CalculatorRandom Fake Address Generator⬛ Aspect Ratio CalculatorOn Base Percentage CalculatorRandom Activity GeneratorSaturn Return CalculatorRandom Poker Hand GeneratorSquare Root (√) CalculatorOPS CalculatorFile Size ConverterSlugging Percentage CalculatorRandom Meal GeneratorRandom Writing Prompt GeneratorLeap Years ListText FormatterCompound Growth CalculatorCaffeine Overdose CalculatorBinary to Gray Code ConverterNumber to Word ConverterIP Subnet CalculatorOctal CalculatorCompare Two StringsRandom Movie PickerLove Compatibility CalculatorBattery Life CalculatorRandom Loadout GeneratorDecimal to BCD ConverterVideo to Image ExtractorBCD to Decimal Converter📅 Date CalculatorMercury Retrograde CalendarStair CalculatorCM to Inches Converter🖱️ Click CounterYouTube Channel StatisticsConnect the Dots GeneratorQuotient and Remainder CalculatorFirst n Digits of PiPER CalculatorAdd Text to ImageName Number CalculatorSHA512 Hash GeneratorPercent Growth Rate Calculator🎰 Gacha Pity CalculatorBingo Card GeneratorAdd Prefix and Suffix to TextImage CompressorRemove AccentOutlier CalculatorWeight Loss CalculatorImage SplitterCoin FlipperVideo CompressorRandom Object GeneratorGray Code to Binary ConverterArc Length CalculatorWhat is my Lucky Number?Day of the Year Calculator - What Day of the Year Is It Today?What is my Zodiac Sign?Lottery Number GeneratorList of Prime NumbersAstrological Element Balance CalculatorSmall Text Generator ⁽ᶜᵒᵖʸ ⁿ ᵖᵃˢᵗᵉ⁾Flip VideoDiff CheckerTime Duration CalculatorURL ExtractorAngel Number CalculatorIP Address to Hex ConverterAcreage CalculatorBcrypt Hash Generator / CheckerRandom Line PickerBreak Line by CharactersRemove Leading Trailing SpacesMultiple Fraction CalculatorNumber ExtractorRandom Time GeneratorHeight Percentile CalculatorAI Language DetectorBinary to BCD ConverterProportion CalculatorMartingale Strategy CalculatorModulo CalculatorWHIP CalculatorDMS to Decimal Degrees ConverterAI Punctuation AdderRandom Chess Opening GeneratorWord Scramble GeneratorPercentile CalculatorCone Flat Pattern (Template) GeneratorDay of Year CalendarRandom Number PickerVideo SplitterLife Path Number CalculatorLong Division CalculatorMandelbrot Set ExplorerRandom Emoji GeneratorPVIFA CalculatorLongest Day of the YearAdjust Video SpeedPVIF CalculatorRandom Chord GeneratorAntilog CalculatorMorse Code GeneratorYouTube Tag ExtractorCollage MakerRatio to Percentage CalculatorBoxing Punch Power CalculatorHypotenuse CalculatorEmail ExtractorSteel Weight CalculatorCrossword Puzzle MakerSum of Positive Integers CalculatorBonus CalculatorRandom User-Agent GeneratorDestiny Number CalculatorFirst n Digits of eAI ParaphraserLunar Calendar ConverterColor InverterPercent to PPM ConverterRandomize NumbersShort Selling Profit CalculatorGrade CalculatorMD5 Hash GeneratorMiter Angle CalculatorSquare Numbers ListFraction CalculatorList RandomizerHTML Compressor🔍 Plagiarism CheckerRounding CalculatorArctan2 CalculatorIs it a Prime Number?Multiplication CalculatorName RandomizerBirth Day of the Week CalculatorMolarity CalculatorTrigonometric Equation SolverDue Date CalculatorExponential Decay CalculatorRandom Group GeneratorYouTube Earnings EstimatorHebrew Calendar ConverterRandom Name GeneratorMAC Address AnalyzerPizza Value CalculatorReverse TextBoiling Point CalculatorNumber RandomizerRemove Line BreaksRock Paper Scissors GeneratorLog (Logarithm) Calculator🎲 Loot Drop Probability CalculatorSort Lines AlphabeticallyHex to BCD ConverterBCD to Binary ConverterBCD to Hex ConverterMedian CalculatorStandard Error CalculatorAverage CalculatorReverse VideoRemove Audio from VideoActual Cash Value CalculatorScientific Notation to Decimal ConverterLog Base 2 CalculatorRoot Mean Square CalculatorSHA3-256 Hash GeneratorAI Sentence ExpanderLbs to Kg ConverterHex to Decimal ConverterConvolution CalculatorRandom String GeneratorAmortization CalculatorMarkup 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 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 CalculatorROT13 Encoder/DecoderAtbash Cipher ToolVigenère Cipher ToolPronunciation IPA ConverterHemingway-Style Readability EditorSentence Length Variance AnalyzerWord Frequency AnalyzerBusiness Days CalculatorAdd Business Days to DateDate Pattern GeneratorHow Long Until CalculatorHow Long Ago CalculatorBirthday Across Cultures CalculatorHijri Calendar ConverterInsulin Sensitivity Factor CalculatorCarb-to-Insulin Ratio CalculatorLean Body Mass to Strength CalculatorOne-Mile Walk Test (Rockport) CalculatorCooper 12-Minute Run CalculatorFFMI CalculatorAPGAR Score CalculatorGlasgow Coma Scale CalculatorWells Score Calculator (DVT/PE)Tennis Score TrackerSoccer xG (Expected Goals) CalculatorCricket Run Rate CalculatorRugby Points CalculatorRace Time PredictorSwimming SWOLF CalculatorYoga Pose Hold TimerFishing Knot Strength CalculatorBike Gear Ratio CalculatorClimbing Grade ConverterWine Pairing SuggesterStandard Drink CalculatorCaffeine Half-Life TrackerSpice Substitution FinderDietary Restriction Recipe FilterMarinade Time CalculatorFermentation Time CalculatorSmoking Wood Pairing GuideFreelance Project Pricing CalculatorSaaS Pricing CalculatorSubscription Cost TrackerSide Hustle ROI CalculatorRemote Work Savings CalculatorCoffee Habit Cost CalculatorGym vs Home Workout Cost CalculatorLunch Cost CalculatorWealth Growth Visualizer1031 Exchange CalculatorRental Yield CalculatorCash-on-Cash Return CalculatorBRRRR Method CalculatorSection 8 Rent CalculatorRoommate Rent SplitterAirbnb Pricing OptimizerStatute of Limitations CalculatorSentence Reduction CalculatorSales Tax Nexus CheckerPatent Filing Fee CalculatorTrademark Class FinderWill Asset Distribution CalculatorWorkers' Compensation CalculatorStopping Distance CalculatorTrip Cost SplitterVehicle Weight Distribution CalculatorTrailer Tongue Weight CalculatorTire Tread Wear CalculatorEngine Compression Ratio CalculatorHeadlight Beam Distance CalculatorCat Litter Box CalculatorAquarium Heater Wattage CalculatorBird Cage Size CalculatorReptile Habitat UVB CalculatorPet Travel Crate Size FinderHorse Hay CalculatorCrochet Hook Size ConverterKnitting Needle Size ConverterKnitting Pattern CalculatorCross-Stitch Floss CalculatorQuilt Binding CalculatorOrigami Paper Size CalculatorPottery Clay Shrinkage CalculatorBeading Pattern CalculatorResin Casting Volume CalculatorEmbroidery Thread Length CalculatorHiking Pace Calculator (Naismith's Rule)Backpacking Food Weight CalculatorTent Footprint Size CalculatorSleeping Bag Temperature Rating GuideKnot Tying Reference ToolStar Visibility CalculatorTide Time CalculatorSun Position CalculatorReynolds Number CalculatorBernoulli Equation CalculatorHeat Transfer CalculatorThermal Expansion CalculatorSpecific Heat Capacity CalculatorGear Ratio Calculator (Mechanical)Pulley System CalculatorHydraulic Cylinder Force CalculatorBelt Length CalculatorCloset Capsule CalculatorStorage Unit Size CalculatorMoving Box Quantity CalculatorGift Card Tip CalculatorGas vs Electric Cost ComparisonPrint Cost CalculatorHair Dye Mixing CalculatorLaundry Detergent Dosage Calculator