Skip to content

Instantly share code, notes, and snippets.

@Godrigos
Created December 27, 2021 12:50
Show Gist options
  • Save Godrigos/f9b6424add14b5d614a4c63e8dcf8756 to your computer and use it in GitHub Desktop.
Save Godrigos/f9b6424add14b5d614a4c63e8dcf8756 to your computer and use it in GitHub Desktop.
List prime numbers between an interval
#include <iostream>
#include <math.h>
using namespace std;
int main(int argc, char const *argv[]) {
// We expect 3 arguments: the program name, the initial value and final value
if (argc != 3) {
cerr << "Usage: " << argv[0] << " INITIAL FINAL (positive integer values)."
<< endl;
return EXIT_FAILURE;
}
// We expect argument 2 to be greater then argument 1
if (atoi(argv[2]) < atoi(argv[1])) {
cerr << "Second argument should be greater then first!" << endl;
return EXIT_FAILURE;
}
if (atoi(argv[2]) >= 2 && atoi(argv[1]) <= 2)
cout << "2 ";
if (atoi(argv[2]) >= 3 && atoi(argv[1]) <= 3)
cout << "3 ";
for (int i = atoi(argv[1]); i <= atoi(argv[2]); i++) {
for (int n = 2; n * n <= i; n++) {
if (i % n == 0)
break;
else if (n + 1 > sqrt(i)) {
cout << i << " ";
}
}
}
cout << endl;
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment