Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange output when trying to find prime numbers Python

Ok, so I admittedly am kind of a noob, and I've been going through a course on udemy for programming. The problem is asking to write a function that finds all the prime numbers up to the number given. So I started writing the following code to extract the numbers that are not even, as well as the numbers not evenly divisible by 3 just to start:

def count_primes(num):
    num_list5 = []
    for i in range(num + 1):
        print(i)
        if i % 2 != 0 or i % 3 != 0:
            num_list5.append(i)
    
    return num_list5

When I call the function with a number of 100 like: count_primes(100) In the output, I get the num_list5 showing all the numbers in the range except for 6 and multiples of 6:

[1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 13, 14 ...]

Its like the if statement is doing an AND operation here... because 6 would be divisible by 2 AND 3. Is this a bug or something? Or am I not understanding and/or operations correctly?

What's weird is that it was working at one point and after making a change and reverting it, it started doing this...

I'm using VSCode and Jupyter notebooks and tried both Python 3.8.5 64-bit and 3.9.4 64-bit on Ubuntu 20.04

like image 908
Arturo Castillin Avatar asked Jan 25 '23 09:01

Arturo Castillin


1 Answers

i % 2 != 0 or i % 3 != 0 is equal to not (i % 2 == 0 and i % 3 == 0) (De Morgan's laws)

It should be i % 2 != 0 and i % 3 != 0

like image 146
Furkan Avatar answered Jan 27 '23 00:01

Furkan