Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to print all prime numbers till 20

C++ Code Example — Series Programs

ADVERTISEMENT

WAP to print all prime numbers till 20

Objective

Write a C++ program to print all Prime numbers up to 20.

Algorithm / Approach

  1. Start an outer loop i from 1 to 20.
  2. Inside, set factors = 0.
  3. Start an inner loop j from 1 to i.
  4. Check for divisibility: if (i % j == 0), increment factors.
  5. After the inner loop, check if the number had exactly 2 factors (factors == 2).
  6. If yes, print i.
main.cpp
#include<iostream>
using namespace std;
int main() {
 int factors;
  for(int i = 1; i<=20; i++) {
   factors = 0;
   for(int j = 1; j<=i; j++) {
    if(i%j ==0)
     factors++;
   }
   if(factors ==2) {
	cout<< i<<"  ";
   }
  }
 cout<< endl;
 return 0;
}

Expected Output

2  3  5  7  11  13  17  19

Explanation of the Program

  • A Prime number is defined mathematically as a number that has exactly two distinct positive divisors: 1 and itself.
  • This algorithm uses brute force. It divides every single number by every number smaller than it and counts the total number of clean divisions. If that count is exactly 2, it's a prime number!

Complexity

Time Complexity O(n^2) - Where n is the range limit (20).
Space Complexity O(1)
ADVERTISEMENT