C Program to Print Prime Numbers From 1 to N
Last Updated :
28 Feb, 2024
Prime numbers are positive integers greater than 1 that have no divisors other than 1 and themselves. In this article, we will learn to generate and display all prime numbers from 1 to N in C programming language.
Prime Numbers from 1 to 100
Algorithm
- Check every number from 1 to N whether it is prime by using isPrime() function.
- In isPrime() Function,
- Iterate from 2 to n/2 and check if the number is divisible by any of the values other than itself.
- If it is divisible by any number, it means the number is not prime, return false.
- If it is not divisible by any number, it means the number is prime, return true.
- If isPrime() returns true, print the number.
- Else continue.
Program to Print Prime Numbers From 1 to N in C
C
#include <stdbool.h>
#include <stdio.h>
bool isPrime( int n)
{
if (n == 1 || n == 0)
return false ;
for ( int i = 2; i <= n / 2; i++) {
if (n % i == 0)
return false ;
}
return true ;
}
int main()
{
int N = 50;
for ( int i = 1; i <= N; i++) {
if (isPrime(i)) {
printf ( "%d " , i);
}
}
return 0;
}
|
Output
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Complexity Analysis
- Time Complexity: O(N2)
- Space Complexity: O(1)
Refer to the complete article Program to print prime numbers from 1 to N for more methods to generate prime numbers.
Related Articles
Share your thoughts in the comments
Please Login to comment...