C++ Exercises: Prints a twin prime which has the maximum size among twin primes less than or equals to n
C++ Basic: Exercise-62 with Solution
Write a C++ program that reads the integer n and prints a twin prime that has the maximum size among twin primes less than or equal to n.
According to wikipedia "A twin prime is a prime number that is either 2 less or 2 more than another prime number—for example, either member of the twin prime pair (41, 43). In other words, a twin prime is a prime that has a prime gap of two".
Pictorial Presentation:

Sample Solution:
C++ Code :
#include <iostream>
#include <cmath>
using namespace std;
int main() {
const int num_primes = 10005;
bool primes[num_primes];
for (int i = 2; i != num_primes; ++i) {
primes[i] = true;
}
for (int i = 2; i != int(sqrt(num_primes)); ++i) {
if (primes[i]) {
for (int j = 2; i * j < num_primes; ++j) {
primes[i*j] = false;
}
}
}
int n;
cout << "Input an integer:\n";
cin >> n;
cout << "Twin primes are:\n";
for (int i = n; i - 2 >= 0; --i) {
if (primes[i] && primes[i-2]) {
cout << i-2 << " " << i << endl;
break;
}
}
return 0;
}
Sample Output:
Input an integer: Twin primes are: 11 13
Flowchart:

C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a C program to swap first and last digits of any number.
Next: Write a C++ program which prints three highest numbers from a list of numbers in descending order.
What is the difficulty level of this exercise?
C++ Programming: Tips of the Day
Why is there no std::stou?
The most pat answer would be that the C library has no corresponding "strtou", and the C++11 string functions are all just thinly veiled wrappers around the C library functions: The std::sto* functions mirror strto*, and the std::to_string functions use sprintf.
Ref: https://bit.ly/3wtz2qA
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook