- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the largest twins in given range in C++
In this problem, we are given two values lValue and hValue. Our task is to find the largest twins in given range.
Two numbers are said to be twin numbers if both of them are prime numbers and the difference between them is 2.
Let's take an example to understand the problem,
Input : lValue = 65, rValue = 100 Output : 71, 73
Solution Approach
A simple solution to the problem is by looping from rValue - 2 to lValue and checking each pair of i and (i+2) for twins and print the first occurred twin.
Another Approach is by finding all prime numbers in the range and then check for the largest pair of i and (i+2) that are prime and
Example
Program to illustrate the working of our solution
#include <bits/stdc++.h> using namespace std; void findLargestTwins(int lValue, int uValue) { bool primes[uValue + 1]; memset(primes, true, sizeof(primes)); primes[0] = primes[1] = false; for (int p = 2; p <= floor(sqrt(uValue)) + 1; p++) { if (primes[p]) { for (int i = p * 2; i <= uValue; i += p) primes[i] = false; } } int i; for (i = uValue; i >= lValue; i--) { if (primes[i] && (i - 2 >= lValue && primes[i - 2] == true)) { break; } } if(i >= lValue ) cout<<"Largest twins in given range: ("<<(i-2)<<", "<<i<<")"; else cout<<"No Twins possible"; } int main(){ int lValue = 54; int uValue = 102; findLargestTwins(lValue, uValue); return 0; }
Output
Largest twins in given range: (71, 73)
Advertisements