Thanks tipaye, those two changes fixed it.
The ' candidate = back_val + 4; ' was a kludge to make it work at all - the '+= 2' obviously better.
I understand the
while on line 31 instead of
for.
Revised cpp below.
I have run it to 99999 primes - the largest prime calculated was 1299709.
Here is the math logic:
A prime is divisible by no number other than itself or 1 ( which is not a prime).
No prime is an even number except 2.
If a candidate is not prime one of the previous primes in the array will divide it with no remainder.
Any divisor of the candidate must be <= the square root of the candidate.
There is an infinite number of primes.
Next I want to tag some properties to each prime -
is it a Merseinne? (rare)
is it only 2 different to a neighbour? (common)
what is its distribution on the number line? (decreasing)
Maybe it should be a class?
What do you think?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
/**
* Brownian Motion 2015
* prime_dev.cpp
*/
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
void prime_calculator()
{
//!< intialize variables
int k, candidate, back_val = 0; //!< last_element array_size,
unsigned int required_size;
float sq_root;
bool prime;
//!< get the number of primes required
cout << "\nHow many primes to calculate? ";
cin >> required_size;
//!< create the prime array fill it with two elements 2, 3
vector<int> prime_array {2,3};
//cout << prime_array.max_size();
//prime_array.reserve(100);
//!< declare the first candidate
candidate = 5;
//!< loop until length of array is = to number required
while (prime_array.size() < required_size)
{
k = 0; //!< k is the index for the modulo test
prime = true;
sq_root = sqrt(candidate);
cout.precision(3);
//cout << "candidate = "<< candidate << " / " <<sq_root << '\t';
//!< does it divide by any element in the array that is less than it's sqrt() ?
while ((prime == true) && prime_array[k] <= sq_root )
{
if(candidate % prime_array[k] == 0) prime = false;
//cout <<" lp "<< k << " res "<< prime << '\t';
k ++ ;
}
if (prime == true)
{
prime_array.push_back(candidate);
back_val = prime_array.back();
candidate = back_val + 2; //!< create new candidate by adding 2 to the last value in the array
}
else candidate += 2; //!< Add another two to move onto the next candidate if false
cout << "index "<< prime_array.size() - 1 << '\t' << prime_array.back() <<endl;
} //!< while 'array < required' return
} //!< End of prime_calculator()
|