I want to check if number, based on lower and upper bound, has prime divisors only 3 and 5 and number should be multiplication of power of 3 and power of 5. My current solution is this. I want to optimize it, since checking powers with for loops isn’t good way in my opinion. Thanks in advance.
JavaScript
x
12
12
1
def checkNum(x):
2
for i in range(1,50):
3
for j in range(1,50):
4
return x == (3**i) * (5**j)
5
6
7
def printResult(l, r):
8
for i in range(l,r):
9
if checkNum(i):
10
print(i)
11
12
Based on comments I think this is the best way:
JavaScript
1
7
1
def checkNum(x):
2
while x%3==0:
3
x = x //3
4
while x%5==0:
5
x = x//5
6
return x==1
7
Advertisement
Answer
I want to optimize it, since checking powers with for loops isn’t good way in my opinion.
Over a range of random numbers, we improve its speed by doing:
JavaScript
1
15
15
1
def checkNum0(x):
2
if x % 2 == 0: # eliminate half the numbers in one test!
3
return False
4
5
while x % 15 == 0: # speed up the process
6
x = x // 15
7
8
while x % 5 == 0:
9
x = x // 5
10
11
while x % 3 == 0:
12
x = x // 3
13
14
return x == 1
15
Or we can use a nested loop and combine both divisions into one:
JavaScript
1
10
10
1
def checkNum(x):
2
if x % 2 == 0: # eliminate half the numbers in one test!
3
return False
4
5
for divisor in (15, 5, 3):
6
while (quotient_remainder := divmod(x, divisor))[1] == 0:
7
x = quotient_remainder[0]
8
9
return x == 1
10