Compute (base raised to exp) modulo modulus efficiently using fast modular exponentiation. A naive approach of multiplying base by itself exp times overflows quickly for large exponents. Instead, use the right-to-left binary method which runs in O(log exp) time. Return null when any argument is null, when modulus is less than or equal to zero, or when exp is negative. By convention return 0 when modulus equals 1.

Examples:

Input: base = 2, exp = 10, modulus = 1000 Output: 24 Explanation: 2 to the power of 10 equals 1024 and 1024 modulo 1000 equals 24 Input: base = 3, exp = 100, modulus = 7 Output: 4 Explanation: 3 to the power of 100 modulo 7 equals 4 by repeated squaring Input: base = 5, exp = 10, modulus = 1 Output: 0 Explanation: Any value modulo 1 is 0 Input: base = 5, exp = 0, modulus = 7 Output: 1 Explanation: Any number to the power of 0 equals 1 Input: base = null, exp = 2, modulus = 5 Output: null Explanation: Null input returns null
Apex Code Editor

Welcome to Lightning Challenge!

How It Works

  • • Write your solution in the code editor
  • • Connect your Salesforce org to test
  • • Submit to check if your solution passes
  • • Use hints if you get stuck

Contest Alert

🏆 #CodeEveryDay July 2026

Contest runs July 1 - 31. Complete challenges to climb the leaderboard!

Only the 31 daily challenges shown during this contest count toward points. Earlier dailies don't carry over.

Wally can't hear you

Please sign in to access the AI Assistant

Sign In