Home   Contact   2017

<< Back

Small application to compute all primes between 2 and N, being N a natural number bigger (>) than 2

//  Primes
//  Primes.c
//
//  Created by K-Zen on 01/04/14.
//  Copyright (c) 2014 APKC.net. All rights reserved.
//
//  This small app calculates all prime numbers between 2
//  and N, given that N is any natural number > 2.

#include <stdio.h>
#include <time.h>

int main(void) {
    unsigned long k = 0, primeCounter = 0;
    clock_t begin, end;
    double timeSpent;
    _Bool isPrime;

    printf("***\n");
    printf("* This small app calculates all prime numbers between 2 and N,\n");
    printf("* given that N is any natural number > 2.\n");
    printf("***\n");
    printf("\n");
    printf("> Type in N: ");
    scanf("%lu", &k);
    
    // Check if N is > 2.
    if (k <= 2) {
        printf("\n");
        printf("> Error: N should be > 2!");
        return 1;
    }
    
    begin = clock();
    // Search for all prime numbers between 2 and k.
    for (unsigned long i = 2; i < k; i++) {
	isPrime = 1; // Raise the flag for each iteration.
	for (unsigned long l = 2; l < i; l++) {
            if (i % l == 0) {
		isPrime = 0;
                break;
            }
	}
        
	// If the flag wasn't lowered then it's a prime number.
	if (isPrime) {
            primeCounter++;
            printf("%lu\n", i);
	}
    }
    end = clock();
    timeSpent = (double) (end - begin) / CLOCKS_PER_SEC;
    
    printf("\n");
    printf("> Primes found: %lu\n", primeCounter);
    printf("> Time Elapsed: %lf minutes\n", timeSpent / 60);
    
    return 0;
}