In C++ write a program that prompts the user to enter two positive integers less than 1,000,000,000 and the program outputs the sum of all the prime numbers between the two integers. Two prime numbers are called twin primes, if the difference between the two primes is 2 or -2. Have a program output all the twin primes and the number of twin primes between the two integers.
NEEDED OUTPUTS FOR PROGRAM:
Enter two positive integers <1,000,000,000: 1 100
-1 and 1 are twin primes.
1 and 3 are twin primes.
3 and 5 are twin primes.
5 and 7 are twin primes.
11 and 13 are twin primes.
17 and 19 are twin primes.
29 and 31 are twin primes.
41 and 43 are twin primes.
59 and 61 are twin primes.
71 and 73 are twin primes.
The sum of prime numbers between 1 and 100 = 1059
The number of twin primes between 1 and 100 = 10
SOURCE CODE:
*Please follow the comments to better understand the code.
**Please look at the Screenshot below and use this code to copy-paste.
***The code in the below screenshot is neatly
indented for better understanding.
#include <iostream>
#include <string.h>
using namespace std;
void twinPrimes(long int number1, long int number2)
{
bool prime[number2 + 1];
memset(prime, true, sizeof(prime));
for (int p = 2; p * p <= number2; p++)
{
if (prime[p] == true)
{
for (int i = p * 2; i <= number2; i += p)
prime[i] = false;
}
}
long int sum=0;
for (int p = number1; p <= number2; p++)
{
if(prime[p] && p!=2)
sum+=p;
}
cout<<"1 and -1 are twin primes."<<endl;
int count =1;
for (int p = number1; p <= number2; p++)
if (prime[p] && prime[p + 2])
{
cout << p << " and " << p + 2 << " are twin
primes."<<endl;
count++;
}
cout<<"The sum of prime numbers between
"<<number1<<" and "<<number2<<" =
"<<sum<<endl;
cout<<"The number of twin primes between "<<
number1<<" and"<<number2<<" =
"<<count<<endl;
}
int main()
{
long int number1, number2 ;
cout<<"Enter Two Positive Integers <1,000,000,000:
";
cin>>number1>>number2 ;
twinPrimes(number1,number2);
return 0;
}
====================
SCREENSHOT:
Get Answers For Free
Most questions answered within 1 hours.