i'm supposed to write a program that
1) finds all prime numbers from 2 to 10,000,000 in iterations powers of 10 (10^2, 10^3, etc.)
2) outputs the sum of the logarithms of all those primes and
3) outputs the ratio of the n value and the current running sum of logs for each iteration.
this is what i have so far, we're supposed to have a boolean function as the prime tester, but this just isn't working. i'm getting all kinds of weird output and i don't know what's wrong. any ideas?
#include <iostream>
#include <math.h>
#include <iomanip>
usingnamespace std;
bool isPrime(int q);
int main (){
int e = 2; // e is for exponent. it goes from 2 to 7.
int n; // n is the assigned variable = 10^e
int p = 2; // p is for prime. it is the last prime number found.
float sum; // sum is the running total.
do{
n = pow(10, e);
if(isPrime(p) == true)
sum += log(p);
cout << fixed << setprecision(5) << sum;
cout << " ";
cout << n;
cout << " ";
cout << fixed << setprecision(5) << sum/n;
cout <<"\n";
e++;
p++;
}while(e < 8 && p < n);
}
bool isPrime(int q)
{
int f; //f is the number each potential prime is divided by
for(f=2;f<q;f++)
{
if(q%f == 0)
returnfalse;
elsereturntrue;
}
}
cool, thanks guys/ladies!
i had been staring at it for too long and had gotten sloppy.
i think i'm close to getting the prime checker loop to work now.
now i got the bool function to work properly, and i think it's getting called to right, but i'm still getting negative numbers as output. here is the revised code.
#include <iostream>
#include <math.h>
#include <iomanip>
#include <stdio.h>
usingnamespace std;
bool isPrime(int candidate);
int main (){
int e = 2; // e is for exponent. it goes from 2 to 7.
int n; // n is the assigned variable = 10^e
int p = 2;// p is for prime. it is the last prime number found.
double sum; // sum is the running total.
do{
n = pow(10, e);
if(isPrime(p) == true)
sum += log(p);
if(isPrime(p) == false)
p++;
cout << fixed << setprecision(5) << sum;
cout << " ";
cout << n;
cout << " ";
cout << fixed << setprecision(5) << sum/n;
cout <<"\n";
e++;
p++;
}while(e < 8 && p < n);
}
bool isPrime(int candidate)
{
int ping = 0; // a prime number should have no more than one divisor greater than 1
int factor = 2; // f is the factor the potential prime is divided by
int remainder; //z is the remainder of the division of the prime and the factor
remainder = candidate%factor;
while(candidate > factor){
if(remainder != 0)
factor++;
if(remainder == 0){
ping++;
factor++;
}
}
if(ping <= 1)
returntrue;
if(ping > 1)
returnfalse;
}
i thought that by assigning value "2" to p inside int main and making it a do...while loop would let me get 2 into the running total as the first prime, but now i think it's screwing it up.