Here is the loop that I created for checking prime numbers in a given interval and outputting those pairs whose difference is 2, problem is its still outputting some non prime numbers at the end.
while (low < high) {
isPrime = true;
if (low == 0 || low == 1) {
isPrime = false;
}
else {
for (i = 2; i < low ; i) {
if (low % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime){
isPrime2 = true;
otrs = low 2;
if (otrs == 0 || otrs == 1) {
isPrime2 = false;
}
} else{
for (c = 2; c < otrs ; c) {
if (otrs % c == 0) {
isPrime2 = false;
break;
}
}
}
if(isPrime && isPrime2) cout<<"The difference of "<<otrs<<" and "<<low<<" is 2."<<endl;
low;
For example this is the output from interval 2-20:
The difference of 4 and 2 is 2. The difference of 5 and 3 is 2. The difference of 7 and 5 is 2. The difference of 9 and 7 is 2. The difference of 13 and 11 is 2. The difference of 15 and 13 is 2. The difference of 19 and 17 is 2. The difference of 21 and 19 is 2.
as you can see the pairs with numbers 4 9 15 21 shouldn't be outputted because they are not prime numbers and I wanted to know whats wrong with my code so I can fix this issue
CodePudding user response:
This is the same code, but prime checking is moved into a separate function.
#include <iostream>
#include <string>
using namespace std;
bool is_prime(unsigned int n) {
if (n <= 1) return false;
for (int i = 2; i < n; i) {
if (n % i == 0) {
return false;
}
}
return true;
}
int main()
{
unsigned int low = 2, high = 20;
bool isPrime, isPrime2;
while (low < high) {
isPrime = is_prime(low);
if (isPrime){
isPrime2 = is_prime(low 2);
}
if(isPrime && isPrime2) cout<<"The difference of "<<low 2<<" and "<<low<<" is 2."<<endl;
low;
}
}
It's easier to understand and already outputs the correct thing:
The difference of 5 and 3 is 2.
The difference of 7 and 5 is 2.
The difference of 13 and 11 is 2.
The difference of 19 and 17 is 2.
It can be further improved by removing unnecessary variables and checking all the odd numbers (because even numbers are not prime obviously). Also prime checking doesn't need to be for all numbers in range [2; n], it can be done in range [2; sqrt(n) 1]
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
bool is_prime(unsigned int n) {
if (n <= 1) return false;
for (int i = 2; i < sqrt(n) 1; i) {
if (n % i == 0) {
return false;
}
}
return true;
}
int main()
{
unsigned int low = 2, high = 20;
if (low % 2 == 0) low;
while (low < high) {
if(is_prime(low) && is_prime(low 2)) cout<<"The difference of "<<low 2<<" and "<<low<<" is 2."<<endl;
low = 2;
}
}
The last improvement would be to not check the same number twice, e.g when low == 5
we check 5 and 7, and on the next we check 7 and 9. So we check every single number twice. How to solve this problem - I'm leaving to you