How can I generate numbers that are powers of two times a prime in Python?
Asked by
!polish the brass
I'm new to Python and want to write a function that accepts a positive integer range and outputs every number that is either prime or equal to a prime multiplied by a power of two. Pure powers of two should count as well, since they can be written as 1 ร 2^n. For example, the range 8 through 16 should produce 8 (2^3), 10 (5 ร 2^1), 11, 12 (3 ร 2^2), 13, 14 (7 ร 2^1), and 16 (2^4). What would be a simple way to implement this?
Answers
Here is a straightforward implementation. This version treats both range endpoints as included and considers powers of two valid by allowing the remaining value to be 1:
```python
def is_prime(n):
if n < 2:
return False
for divisor in range(2, int(n ** 0.5) + 1):
if n % divisor == 0:
return False
return True
def is_special(n):
while n % 2 == 0:
n //= 2
return n == 1 or is_prime(n)
def special_numbers(start, end):
return [n for n in range(start, end + 1) if is_special(n)]
print(special_numbers(8, 16))
```
The output is `[8, 10, 11, 12, 13, 14, 16]`. In Python, `range(start, end + 1)` is used here because the normal end value is excluded.
Reply to this answer
You can also think of each number as `odd_part ร 2^k`. Removing factors of two leaves the odd part. For example, 12 becomes 3 after dividing by 2 twice, so it qualifies because 3 is prime. This is easier to understand at first than using bit operations; optimizations such as shifting bits can come later.
Reply to this answer
A useful approach is to repeatedly divide each number by 2 while it is even. The remaining odd part will be either 1 or a prime if the original number matches your rule. You can then test that odd part with a basic prime-checking function.
Reply to this answer
Before writing the filtering logic, decide what โrangeโ means. The example includes both 8 and 16, so the code should include the upper endpoint. Also, โpickโ appears to mean print or return all matching numbers rather than randomly choose one.
Reply to this answer
Add your answer
Answers are reviewed before publication.
!polish the brass: Iโm completely new to coding, so Iโll probably start with a simple Python editor and first learn how to loop through and print a range.