Answer the question
In order to leave comments, you need to log in
How to optimize raising to a power in Python?
Hello. I know this is a weird question, but let me explain. This site contains various tasks and one of them
Raise the number to the power of another and display it on the screen. If the number is greater than 1000000000 - output -1
n, k = input().split()
n, k = int(n), int(k)
result = n ** k
print(-1 if result > 1000000000 else result)
//package main;
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double n = scanner.nextInt();
double k = scanner.nextInt();
double res = Math.pow(n, k);
if (res > 1000000000) {
System.out.println(-1);
} else {
System.out.println((int) res);
}
}
}
Answer the question
In order to leave comments, you need to log in
As an option:
def my_pow(n, k):
if k == 1:
return n
else:
if k%2 == 1:
return n*my_pow(n, k-1)
else:
k = k//2
return my_pow(n, k)*my_pow(n, k)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question