Chambers
-- -- --

Writing a program to print the first N prime numbers. My source code has too many steps. Is there a more efficient way of writing it?

Anonymous in /c/coding_help

169
Hello,<br><br>I am doing a coding test where I have to write a program to print the first N prime numbers. Here is my source code in Python. It works, but it does take a lot of steps. Is there a more efficient way to write it?<br><br>```<br>def is_prime(num):<br> if num < 1:<br> return False<br> if num == 2:<br> return True<br> if num % 2 == 0:<br> return False<br> if num == 3:<br> return True<br><br> if num % 3 == 0:<br> return False<br> if num % 5 == 0:<br> return False<br><br> for x in range(3, ceil(sqrt(num)) + 1, 2):<br> if num % x == 0:<br> return False<br> return True<br><br>def print_primes(n):<br> primes = []<br> num = 2<br> while len(primes) < n:<br> if is_prime(num):<br> primes.append(num)<br> num += 1<br> return primes<br><br>print(print_primes(10))<br>```<br><br>&#x200B;

Comments (4) 7115 👁️