Here's a function in Python that calculates the first n
prime numbers:
main.py301 chars14 lines
The function starts with an empty list called primes
, and an initial value of num = 2
, which is the first prime number. We then use a while
loop to keep finding prime numbers until we have n
primes.
Inside the loop, we set a flag variable is_prime
to True
, which we assume for each value of num
. We then use a for
loop to iterate through every number from 2 to num-1
, checking if num
is divisible by any of them (if it is, then num
is not prime). If we find that num
is divisible by any of those numbers, we set is_prime
to False
and break out of the loop.
If is_prime
is still True
after the for
loop finishes, it means that num
is a prime number, so we add it to the primes
list. Finally, we increment num
by 1 and continue the loop.
Once we have n
primes in the primes
list, we return it from the function.
To use this function, you can simply call it with the number of primes you want to find, like this:
main.py69 chars3 lines
gistlibby LogSnag