Recursive fast power MEDIUM Expresii (BAC) Recursivitate (BAC) 25 XP 0 solved
Mobile coding works. A laptop is faster for long sessions.

Problem

Three natural numbers `x`, `n`, and `m` are read. Print the value of `x^n` modulo `m`, computed using **a recursive function** that exploits exponentiation by squaring (the number of calls must be of order `log2(n)`). Define a recursive function `power(x, n, m)` that returns `(x^n) mod m`, using the relation: ``` power(x, 0, m) = 1 mod m power(x, n, m) = (power(x, n/2, m))^2 mod m, if n is even power(x, n, m) = ((power(x, n/2, m))^2 * x) mod m, if n is odd ``` Note: do NOT compute `x^n` directly and then take modulo (intermediate values can be enormous). Reduce modulo `m` after every multiplication.

Input format

Input input.txt

The program reads from standard input, separated by spaces, three natural numbers `x`, `n`, and `m`. - `0 <= x <= 1.000.000` - `0 <= n <= 1.000.000.000` - `1 <= m <= 1.000.000.007` - The solution must be recursive, with call depth of order `log2(n)`.

Output format

Output output.txt

The program prints a single natural number: `(x^n) mod m`, followed by a newline.

Example

input
2 10 1000000
output
1024

Ready to solve this challenge?

Create a free account to write code, submit solutions, and track your progress.

⌨️ Keyboard Shortcuts

Code Editor
Run Code
Ctrl Enter
Submit Code
Ctrl Shift Enter
Format Code
Shift Alt F
Toggle Comment
Ctrl /
Undo
Ctrl Z
Redo
Ctrl Y
Navigation
Global Search
/
Show Shortcuts
?
Close Modal
Esc

🔍 Interactive Debugger

0 / 0

Analyzing your code...

📦 Variables

No variables yet

📚 Call Stack
main() line 1
📤 Output
We use cookies

Essential cookies are always active. You can choose to enable preference and analytics cookies. Learn more