WAP to print all prime numbers till 20
Objective
Write a C++ program to print all Prime numbers up to 20.
Algorithm / Approach
- Start an outer loop
ifrom 1 to 20. - Inside, set
factors = 0. - Start an inner loop
jfrom 1 toi. - Check for divisibility:
if (i % j == 0), incrementfactors. - After the inner loop, check if the number had exactly 2 factors (
factors == 2). - 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)