I'm new to python and in order to learn I'm trying to solve a problem as an exercise.
N is a integer between [1, 10^9] K is a list of length <= 40 of random distinct prime numbers that are all equal or less to N.
My code has to find the quantity of number that are <= N that are not divisible by any number of the list K.
I've written the following code:
first_line = input().split()
second_line = input().split()
n = int(first_line[0])
list_of_primes = second_line
all_multiples_set = set()
for i in range(len(list_of_primes)):
prime = int(list_of_primes[i])
# Creates a set of all multiples numbers of this prime that are equal or less than N.
one_multiple_set = set(range(prime ,n if n % prime != 0 else n + prime ,prime ))
# Makes a Union of this set with the previous sets of multiples, thus getting all multiples of a and b.
all_multiples_set = all_multiples_set.union(one_multiple_set)
print(n - len(all_multiples_set))
The first input consist of 2 numbers: N and length of K respectively. (ie. "10 3").
The second input is a series of length of K primes that are less or equal to N. (ie. "2 3 7").
The output should be a integer that represents the quantity of number equal or less than N that are not dividable by any number in list K. (ie. "2" in this case)
I know my code works for some cases, but unfortunately the platform where I found this puzzle does not tell me for which cases my code does not work, it only tells me that it does not work for some cases.
I believe it is a question of memory. Given that 10^9 is a very large number, but it could also be an error that I'm not seeing.
I would appreciate some guidance in how to improve my code or a suggestion of a better approach. It is worth noticing that since this is an exercise, I can not import modules and also since I'm trying to learn, I would appreciate an explanation of why my code is ineficiente.
EDIT:
Execution time is also a factor. The code has 1 second max run time.
On my first try I wrote this code:
linha1 = input().split()
linha2 = input().split()
n = int(linha1[0])
s = linha2
x = len(s)
value_to_add = 0
value_to_subtract = 0
for i in range(1 << x):
single_set = []
multiply = 1
for j in range(x):
if i & (1 << j):
single_set.append(int(s[j]))
for num in single_set:
multiply *= num
if multiply > n:
break
if len(single_set) == 1:
value_to_add += n//single_set[0]
elif len(single_set) > 1:
value_to_subtract += n//multiply
print(n - value_to_add + value_to_subtract)
It also gets the right answer, but it takes to long to run.