A lucky number is found by listing all numbers up to n. 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32 And then remove every second number so we get: 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31 Now the next numbers after 1 here is 3 so now remove every third number: 1,3,7,9,13,15,19,21,25,27,29 Now the next number after 3 is 7, so now remove every seventh number: 1,3,7,9,13,15,21,25,27,29 And the next number after 7 in our list is 9 so now remove every ninth number. etc
The remaining numbers are lucky numbers: 1,3,7,9,13,15,21,25,31
Hello, I am a relatively new Python programmer who is trying to figure this out. I did not even come close to solving this, and I want them up to the 100 billions so an advice of the best way to go about this is welcome. here is my best try to get this done in Numpy:
import numpy as np
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31])
b = a[::2] #using skip of 2 on our array
c = b[::3] #using skip of 3 on our array
d = c[::7] #using skip of 7 on our array
e = d[::9] #using skip of 9 on our array
print(e)
It returns only 1 so this requires more advanced programming to find the lucky numbers, I need some clever programming in order to automatically find the next skip also since I can't input millions of skips like I have done here with the skips of 2, 3, 7 & 9.
CodePudding user response:
IIUC, one way using while
loop with checker:
def find_lucky(n):
arr = list(range(1, n 1))
done = set()
ind = 1
while len(arr) >= (i:= arr[ind]):
if i in done:
ind = 1
else:
del arr[i-1::i]
done.add(i)
return arr
Output:
find_lucky(32)
# [1, 3, 7, 9, 13, 15, 21, 25, 31]