#include <iostream>
usingnamespace std;
int sumOfDigits(int x) // CALC SUM OF DIGITS
{
int r, sum=0;
while(x!=0)
{
r = x%10;
x=x/10;
sum+=r;
}
return sum;
}
int prim(int x) // RETURNS 1 IF PRIME, 0 IF IS NOT
{
int v = 1;
for(int i = 2; i<=(x/2);i++)
{
if(x%i == 0) v = 0;
}
return v;
}
int main()
{
int i=18 // BECAUSE I'VE CHECKED FIRST 17 NO.
int contPrim = 7 // BECAUSE I'VE FOUND 7 PRIME NO.
int contSum = 0;
while(i<10000000)
{
if((i&0) || (i%3==0) || (i%5==0) || (i%7==0) || (i%11==0) || (i%17==0) ) i+=1;
elseif(prim(i)) {
contPrim+=1;
if(sumOfDigits(i)==14) contSum+=1;
i+=1;
} else i+=1;
}
cout << "there are " << contPrim << " prime numbers \n and " << contSum <<" have the sum of digits equal to 14. "<< endl;
}
#include <iostream>
#include <cmath>
bool is_prime(int num);
int sumOfDigits(int x);
int main(void)
{
int sumy = 0, prime = 7;
constint PRIME_LIMIT = pow(10, 7);
for (int i = 19; i < PRIME_LIMIT; i+=2)
{
if ( is_prime(i) )
{
prime++;
if (sumOfDigits(i) == 14) sumy+=1;
}
}
std::cout << "no of prime is " << prime << "\n and from them " << sumy << " has sumOfDigits = 14";
return 0;
}
bool is_prime(int num)
{
if (num < 2)
returnfalse;
for (int i = 2; i <= (int)sqrt(num); i++)
{
if (num % i == 0)
returnfalse;
}
returntrue;
}
int sumOfDigits(int x)
{
int n, r, sum=0;
while(x!=0)
{
r = x%10;
x=x/10;
sum=sum+r;
}
return sum;
}
//change while(x!=0) to
while(x!=0 && sum < 14) // only sum digits until equal or greater than 14
in int prim(int x):
1 2 3 4 5 6 7 8 9 10 11 12
int prim(int x) // RETURNS TRUE IF PRIME, FALSE IF IS NOT
{
int v = 1;
//for(int i = 2; i<=(x/2);i++)
for (int i = 3; i * i <= x && v; i +=2) // only check odd numbers, and only until a factor is found.
{
v = (x % i != 0);
}
return v;
}
(in fact, ( i & 0 ) will always be false for non-zero integers, so none of the other comparisons are done)
Could make another small change - doesn't have a lot of effect, though, but probably more readable, don't have to figure out if or why i is incremented twice, and same as prim() only need to check odd numbers: (start out with i as an odd number, naturally)
1 2 3 4 5 6
elseif(prim(i)) {
contPrim+=1;
if(sumOfDigits(i)==14) contSum+=1;
// take this out: i+=1;
} // and this: else
i+=2;