954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

twin primes ..not quite working ..why?

Good day all,
I've been working on this code for a for a while now and I can't seem to find what's wrong.
I am supposed input two numbers and return if this is a twin prime number by just outputting true or false. My program compiles and runs but I am getting false for all my numbers. Twin prime numbers are numbers that are prime and differ by 2
for example, 3 and 5 are prime numbers and differ by 2
Can someone please check my code and tell me what part of it is wrong...
Much appreciated...

#include <iostream>
using std::cout;
using std::endl;
using std::cin;


bool isPrime(int a){
	for (int i=1; i!=a / 2; i++)
     	{
     int o=0;
     		if (a % i == 0)
     		{
     			++o;
     		}
			if ( o != 1)
				return true;
			else 
				return false;
     	}

}
bool isTwinPrime(int a, int b){
  if (isPrime(a) && isPrime(b) && 2 == b - a)
    return true;
  else
    return false;
  }


int main()
{
  int a, b, isPrime;
cin >> a;
cin >> b;
using namespace std;
cout<< boolalpha<< isTwinPrime (a, b)<<endl;

return 0;
}
rocky1821
Newbie Poster
5 posts since Sep 2007
Reputation Points: 10
Solved Threads: 0
 

The loop beginning on line 8 will never ever execute more than once because of the return statements on lines 16 and 18.

>>&& 2 == b - a ==> line 23
That will not work when the value of a > b. You need to consider someone entering 5 and 3 instead of the other way around.

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You