CSC115 · 2081 · 5 marks
Write a program to display first 50 prime numbers.
Write a program to display first 50 prime numbers. [5]
Program to Display First 50 Prime Numbers
Given Data
- Required output: first 50 prime numbers
- Marks: 5
Concept
A prime number is an integer greater than 1 whose only positive divisors are 1 and itself. To generate the first 50 primes, we test successive integers starting from 2, counting each prime until 50 are found.
Program (C)
#include<stdio.h>
#include<conio.h>
void main()
{
int num, i, count, primeCount;
clrscr();
primeCount = 0; /* number of primes found so far */
num = 2; /* start from smallest prime */
printf("First 50 Prime Numbers are:\n");
while(primeCount < 50)
{
count = 0; /* 0 = prime, 1 = not prime */
for(i = 2; i <= num/2; i++) /* check divisors up to num/2 */
{
if(num % i == 0)
{
count = 1;
break;
}
}
if(count == 0) /* num is prime */
{
printf("%d\t", num);
primeCount++;
}
num++;
}
getch();
}
Note: an inner loop written as
i < numis logically correct, it simply checks more divisors than necessary. Usingi <= num/2(ori*i <= num) is more efficient, and both give the same correct output.
Sample Output
First 50 Prime Numbers are:
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229
Verification of Output
Counting the listed primes: 5 rows of 10 = 50 primes. The 50th prime is $229$, which is correct.
Explanation
| Part | Purpose |
|---|---|
primeCount < 50 | Loop continues until exactly 50 primes are found |
Inner for loop | Tests whether num has any divisor |
num % i == 0 | Marks num as composite |
count == 0 | Indicates num is prime |
primeCount++ | Records each prime found |
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.