Search This Blog

Simplicity is the ultimate sophistication.” — Leonardo da Vinci
Contact me: sreramk360@gmail.com

Friday 27 March 2015

program to count the number of prime numbers from 1 to limit



Program to count the number of prime numbers from 1 to limit
 

/*
* program to count the number of prime numbers from 1 to limit
*/
#include <stdio.h>
#include <conio.h>

int checkPrime(int val)
{ // tests if the given number is prime or not
    int i;
    if(val == 1 || val == 0)
        return 0;
    for(i=2; i<=val/2; ++i)
        if((val%i) == 0)
                return 0;
    return 1;
}

int noOfPrimes(int lim)
{// this calls the function checkPrime to test if the number is prime
    // if it is prime, 'count' is incremented.
    int i, count = 0;
    printf("\nlist of prime numbers from 2 to %d", lim);
    for(i=2; i<=lim; ++i)
        if(checkPrime(i))
            {
                ++count;
                printf("\n%d", i);
            }
    return count;
}

int main() /// the runtime complexity of this program is O(N^2)
{
    int lim;
    printf("enter the limit:");
    scanf("%d", &lim);
    printf("number of prime numbers from 2 to %d is %d", lim, noOfPrimes(lim));
    return 0;
}




copyright (c) 2015 K Sreram.
About my blog
 
 

No comments:

Post a Comment

Featured post

Why increasing complexity is not good?

“ Simplicity is the ultimate sophistication.” — Leonardo da Vinci Why is complicating things wrong ? - K Sr...