Here's the cool number problem given to me by my senpai in competitive programming:
A cool number is a number that can be at the same time written as the square of a whole number and the cubic of another whole number.
Write a program in Python that returns the number of cool numbers for every given [m, M] with 1 <= m < M <= 10^9
Input data: m and M 2 integers
Output format: the number of cool numbers in [m, M]
Time execution limit: 1 second
Memory space limit: 64 Mo
First I naively thought about testing for each number between m and M, but that took more than 10 seconds just for values between 1 and 10e6.
But as I was thinking about a way to check if the output is correct, I thought about having a maximum of roots, lets say if there were 64 numbers in the [1, 64] range, the sixth root of that range would have 4 numbers in [1, 4], that's when it hit me, I can simply have the sixth root of my range and those are the roots of my cool numbers, I just have to count them and raise them to the power of 6 if I want to know what my cool numbers are.
So yeah here's my code that does exactly that, while also checking for execution time, I'll check for how much space it takes later
from time import perf_counter
from personalMath import root, ceil, floor
# input and declaring variables
m, M = [int(float(x)) for x in input().split()]
sixthm = floor(root(m, 6, 10))
sixthM = ceil(root(M, 6, 10))
counter = 0
# magic
t1 = perf_counter()
n = sixthM - sixthm + 1
t2 = perf_counter()
for x in range(sixthm, sixthM + 1):
print("Cool number {}: {}".format(x, x**6))
t3 = perf_counter()
findTime = t2 - t1
printTime = t3 - t2
findAndPrintTime = t3 - t1
# output
print("There are {} cool numbers between {} and {}".format(n, m, M))
print("Finding time: ", findTime)
print("Printing time: ", printTime)
print("Total execution time: ", findAndPrintTime)
and here are my functions
def root(x, n, m):
return round(x**(1/n), m)
def floor(n):
return int(n//1)
def ceil(n):
return int((n//1) + 1)
If you could give me your thoughts, I'd highly appreciate it!