Under construction

Still being built. Things may change

Exponentiation

Interview

Time limit3sMemory limit1024 MB

Summary
Given alpha, beta, and m, compute x^beta + 1/x^beta mod m, where x + 1/x = alpha and all inputs are below 2^64.
Level

Medium5 of 10

Topics
Math, Matrix, Number theory
Solved
No attempts yet

Problem

Exponentiation is a basic mathematical operation that raises a base number to an exponent to obtain a result. In the expression ana^n, aa is the base and nn is the exponent, meaning aa is multiplied by itself nn times. The result is called the nn-th power of aa. For example, 23=2×2×2=82^3=2 \times 2 \times 2=8 and 52=5×5=255^2=5 \times 5=25. In the first case, the base is 22 and the exponent is 33. In the second case, the base is 55 and the exponent is 22. Exponentiation is used in many areas, such as solving equations and cryptography.

In many cryptographic algorithms based on number theory, such as RSA (Rivest-Shamir-Adleman) and Diffie-Hellman, modular exponentiation is a basic operation. Modular exponentiation raises a base to an exponent and then takes the remainder modulo a modulus. It is computationally heavy, but it can be carried out fairly quickly even for very large numbers.

Let x+1x=αx+\frac{1}{x}= \alpha, where α\alpha is a positive integer. Write a program that computes xβ+1xβ mod mx^\beta + \frac{1}{x^\beta} \bmod m for given positive integers β\beta and mm.

Input

The input is one line with three space-separated positive integers α\alpha, β\beta, and mm. Each of α\alpha, β\beta, and mm is less than 2642^{64}.

Output

Output xβ+1xβ mod mx^\beta + \frac{1}{x^\beta} \bmod m. You may assume that xβ+1xβx^\beta + \frac{1}{x^\beta} is an integer. If there are multiple solutions, you may output any of them in the range from 00 to m−1m-1.

Hint

xx can be a complex number. For example, if α=1\alpha=1, then xx is either 1+3i2\frac{1 + \sqrt{3}i}{2} or 1−3i2\frac{1 - \sqrt{3}i}{2}. However, xβ+1xβx^\beta + \frac{1}{x^\beta} is always an integer in this problem.

Examples4

  1. Example 1

    Input
    1 2 3
    
    Expected output
    2
    
  2. Example 2

    Input
    5 4 321
    
    Expected output
    206
    
  3. Example 3

    Input
    3 3 333
    
    Expected output
    18
    
  4. Example 4

    Input
    8 8 888
    
    Expected output
    626