Safe Power (Non-negative Exponent)
Python
Easy
4 views
Problem Description
Read two integers a and b. Output a^b modulo 1000000007. If b is negative or input invalid, output ERROR.
Input Format
One line: a b.
Output Format
One integer or ERROR.
Official Solution
import sys
p=sys.stdin.read().strip().split()
MOD=1000000007
if len(p)<2:
sys.stdout.write('ERROR')
else:
try:
a=int(p[0])%MOD
b=int(p[1])
if b<0:
sys.stdout.write('ERROR')
else:
res=1
base=a
e=b
while e>0:
if e&1:
res=(res*base)%MOD
base=(base*base)%MOD
e//=2
sys.stdout.write(str(res))
except Exception:
sys.stdout.write('ERROR')
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!