H
H
hellcaster2019-11-18 15:29:28
Python
hellcaster, 2019-11-18 15:29:28

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

It seems that there is nothing complicated, but the thing is that on the 18th test, the Time Limit error appears. How to bypass it? At first I wrote an algorithm in Java and it went great, but in Python it doesn’t want to do almost the same ((
Python

n, k = input().split()
n, k = int(n), int(k)
result = n ** k

print(-1 if result > 1000000000 else result)


Java

//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

2 answer(s)
F
Farwisdomer, 2019-11-18
@web_Developer_Victor

https://en.wikipedia.org/wiki/Exponential_by_sq...

I
Ivan Melnikov, 2019-11-18
@immelnikoff

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)

You can probably tweak the code for yourself.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question