Created
February 19, 2016 06:15
-
-
Save ashwin67/58ce66a4d0544633c870 to your computer and use it in GitHub Desktop.
List some prime numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// While the day to day coding (or rather debugging) keeps me occupied, nothing matches the happiness in | |
// coding something just for the sake of it. Recently, I started reading "The man who knew infinity", a biography | |
// about Ramanujan. That got me interested about prime numbers. Now, mathematics is close to coding in some ways. | |
// So, I thought, let me try to write some programs on primes. | |
// This is a first of that kind. A purely intuitive program. | |
// Can be run at http://cpp.sh/ | |
// Program 1: List some prime numbers | |
#include <iostream> | |
#include <string> | |
#define P 50 // How many primes to show (minimum 2) | |
void list_primes(void) | |
{ | |
int a[P]; // Array to hold the prime numbers. "2" is not in this array. | |
int b[P]; // Array to keep track of the count w.r.t to a prime. When this count is | |
// equal to its respective a[i], the number is composite. See code to understand. | |
int n=1; // How many primes are generated? (+1) | |
bool c; // composite or not? | |
a[0] = 3; // First prime initialization | |
b[0] = 0; | |
std::cout << "First " << P << " primes: 2, 3, "; | |
for (int x=5; ;x+=2) { // All even numbers above 2 are anyway composite. So, skip them. | |
c = 0; // Initialize x as a prime. Not guilty until proven. | |
if (n >= P-1) { | |
break; | |
} | |
for (int i=0;i<n;i++) { // Example. 3 is prime. Then every third increment is a composite. 9, 15, 21 etc. | |
b[i]++; // Also, 7 is prime. Subsequently, every 7th increment is. 21, 35, 49 etc. | |
} //... And so on... | |
for (int i=0;i<n;i++) { // b[i] holds these increment count w.r.t each prime. | |
if (b[i]==a[i]) { // The count is initialized to 0 each time it reaches its respective prime | |
b[i] = 0; | |
c = 1; // Flag as composite | |
} | |
} | |
if (c == 0) { // Prime. | |
a[n] = x; | |
b[n] = 0; | |
n++; | |
std::cout << x << ", "; | |
} | |
} | |
} | |
int main() | |
{ | |
list_primes(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It seems that this algorithm is known as https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes