Youwrite a program to find first 50 prime numbers
Question
Youwrite a program to find first 50 prime numbers
Solution
Sure, here is a simple Python program that prints the first 50 prime numbers:
def is_prime(n):
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
i = 3
while i * i <= n:
if n % i == 0:
return False
i += 2
return True
count = 0
num = 2
while count < 50:
if is_prime(num):
print(num)
count += 1
num += 1
Here's how it works:
-
The
is_prime(n)function checks if a numbernis prime. It first checks ifnis less than or equal to 1, in which case it returnsFalsebecause 1 is not a prime number. It then checks ifnis 2, in which case it returnsTruebecause 2 is a prime number. It then checks ifnis divisible by 2, in which case it returnsFalsebecause no even number greater than 2 can be prime. Finally, it checks ifnis divisible by any odd number up to the square root ofn. Ifnis divisible by any such number, it returnsFalse; otherwise, it returnsTrue. -
The main part of the program initializes a counter
countto 0 and a numbernumto 2. It then enters a loop that continues untilcountreaches 50. In each iteration of the loop, it checks ifnumis prime. Ifnumis prime, it printsnumand incrementscountby 1. Whether or notnumis prime, it incrementsnumby 1.
Similar Questions
Write a program primes.py that reads a positive integer from standard input, and determines whether or not the number is prime.
Complete the code to find if a given number is a prime number? The program will take a positive integer greater than 1 as input and indicate if it is a prime number by saying "prime", and if it is not a prime number saying "not a prime". Note there are 3 places in the given code that you need to fix for this code to work properly and give the expected output.
Write a single line Python code to print all the prime numbers between 1 and 200.
write easies code for me : Write a program in C to find if a number is prime or not.
A number is chosen at random from 1 to 50. Find the probability of not selecting odd or prime numbers.
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.