Checking if the whole number is prime, and if all its digits are too

That was an easy one to solve but the problem lies in the efficiency since it checks every single digit of the number while converting to integers. I’m receiving TLE (i.e. Time Limit Exceeded) on the site so I have to increase its performance.

So its hard to explain but the exercise asks for the return value to be “Super” when the number is prime and all of its digits are too, return “Primo” when the number is prime but its digits are not, return “Nada” When the whole number is not prime. The test cases end with EOF.

Its worth mentioning that only built-in modules are accepted by the site. I tried using the well known (and much faster) sympy.isprime method, but it’s from a 3rd party module so it wasn’t accepted, sadly.

Again, I solved it, but I need a bump in the efficiency since there are 1018 numbers in the test cases and more than 200 test cases and I need to solve it in 2 seconds:

def is_prime(n):
    if n in range(0, 2):
        return False
    for i in range(2, n):
        if n % i == 0:
            return False
    return True

while True:
        data = input()
    except EOFError:
    if is_prime(int(data)):
        for j in data:
            if not is_prime(int(j)):


The easiest improvement to make is to only go up to n**.5 inisprime This yields a quadratic speedup. The next obvious improvement is to not convert each digit to an int, but rather just use if j not in "2357":. This saves time in two ways: First, it skips an int conversion, and secondly, it uses one check instead of a for loop.

Source : Link , Question Author : Mateus , Answer Author : Oscar Smith

Leave a Comment