Prime Number Check

Jan 16, 2013 at 3:22pm
Hi, I am a newbie in c++ programming. I wrote a simple code to check if a number is prime or not. But code is not working correctly. It checks some numbers correctly and some numbers incorrectly. Can some one identify mistakes in my code?? please.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
unsigned long a,b;
    cout<<"Enter a number: ";
    cin>>a;
    for (int i=2; i<a; i++)
    {
    b=a%i;
    if(b == 0)
              {
              cout<<"Not Prime!";
              cout<<endl;
              break;
              }
    else
    {
        cout<<"Prime."<<endl;
        break;
    }
    }
    return 0;


It shows 49 as a prime number.. :(
Last edited on Jan 16, 2013 at 3:24pm
Jan 16, 2013 at 3:33pm

if(b==0) means you have found an not prime number, but you incorrectly assume that if b!=0 (the else statement), that it is a prime.
Jan 16, 2013 at 3:40pm
The problem is the loop terminates too soon. If b==0 the number is not prime, that is ok. But in order for it to be prime, the loop must continue checking all the other values of i.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
    unsigned long a;

    cout<<"Enter a number: ";
    cin>>a;

    bool prime = true;

    for (int i=2; i<a; i++)
    {
        if (a%i == 0)
        {
            prime = false;
            break;
        }
    }

    if (prime)
        cout<<"Prime."<<endl;
    else
        cout<<"Not Prime!" <<endl;

Jan 16, 2013 at 5:49pm
I will post my code for the Sieve of Eratosthenes algorithm. I got helped yesterday finishing it and it got quite clear and understandable.Just examine it and if you don't get the idea - don't worry it took me some time to get to the end.
Here is it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/* Sieve of eratosthenes project for finding primes
up to 100 */

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    int max=100;
    cout <<"Enter max number: \t";
    cin >> max;
    vector<bool> sequence(max,true);
    sequence[0]=false; 
    sequence[1]=false;

    for (int i=2; i<max;++i)
        if (sequence[i])
            for (int x=i+i; x<max; x+=i)
                sequence[x] = false;

    for (int z=0;z<max;++z)
        if (sequence[z])
            cout << "Prime number: " << z <<endl;

    return 0;
}
Last edited on Jan 16, 2013 at 5:53pm
Jan 16, 2013 at 7:34pm
Hi, I've just started C++ as well, my simple code for prime number is :


#include "stdafx.h"
#include <iostream>
#include <math.h>
using namespace std;

int main() {
int n = 0;
bool is_prime = true;

cout << "Enter a number and press ENTER: ";
cin >> n;

for (int i = 2; i <= sqrt(double(n)); i++) {
if (n % i == 0)
is_prime = false;
}

if (is_prime)
cout << "Number is prime." << endl;
else
cout << "Number is not prime." << endl;

system("PAUSE");

return 0;
}


code findes primes to all numbers...
Last edited on Jan 16, 2013 at 8:03pm
Jan 16, 2013 at 8:14pm
@usmiech Well done. The test for square root is a useful optimisation, it cuts down on unnecessary iterations of the loop.

Just one suggestion. As presented above, the sqrt() function is called on each iteration of the loop, which is detracting a bit from the advantage gained. So I'd suggest calling it just once before the loop begins:
1
2
    int limit = sqrt(double(n));
    for (int i = 2; i <= limit; i++) {
Jan 16, 2013 at 8:53pm
I got it. Thank you all. this forum is much better than my programming class.
Jan 16, 2013 at 9:02pm
I also decided to write a program that determines whether a number is prime.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

int main()
{
	while ( true )
	{
		std::cout << "Enter a non-negative number (0 - exit): ";
		size_t x = 0;
		std::cin >> x;

		if ( !x ) break;

		bool prime = x == 2 || x % 2;

		for ( size_t i = 3; prime && i < x / 2; i += 2 )
		{
			prime = x % i != 0;
		}

		std::cout << x << " is " << ( prime ? "" : "not " ) 
		          << "a prime number\n" << std::endl;
	}

	return 0;
}
Last edited on Jan 21, 2013 at 6:43pm
Jan 16, 2013 at 9:11pm
Thx Chervil :)
Jan 18, 2013 at 7:27pm
#include<iostream.h>

int main()
{
int n;
int i;
int flag= 0;
cout<<"Enter the number";
cin>>n;
//cout<<endl<<n;
for(i=2;i<n;i++)
{
flag = n % i;
if(flag == 0)
{
cout<<"Not prime";
break;

}
flag++;


}
if(flag>0)
{
cout<<"Prime";

}


system("PAUSE");
cin.get();
return 0;


}
Jan 21, 2013 at 6:01pm
Hi, my next try ...
Code for prime number... but ...
It returnes factors and a next prime.... Unfortunately just for not prime number... But I started learning C ++ 10 days ago....sorry :).... Every day I am getting better ;)



#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
bool prime(int n);
void get_divisors (int n);
void next_prime (int n);



int main(){
int i;
while (true) {
cout << "Enter a num (0 = Exit) and press ENTER: ";
cin >> i;
if (i == 0)
break;
if (prime (i))
cout << "num is prime" << endl;
else
cout << "num is not prime" << endl;
get_divisors (i);
cout << endl;
next_prime (i);
cout << endl;
}
system ("PAUSE");
return 0;
}

bool (prime (int n)){
int i;
int limit = sqrt (double(n));
for (i = 2; i<= limit; i++){
if (n % i == 0)
return false;
}
return true;
}
void get_divisors (int n) {
int i;
int sqrt_of_n = sqrt (double(n));
for (i = 2; i <= sqrt_of_n; i++)
if (n % i == 0){
cout << i << ", ";
get_divisors (n / i);

return;
}
cout << n;
}
void next_prime (int n) {
int i;
int limit = sqrt (double(n));
for (i = 2; i <= limit; i++)
if (n % i == 0){
next_prime (n + 1);

return;
}

cout << "Next Prime: " << n;
}
Jan 21, 2013 at 6:47pm
This function

void next_prime (int n) {
int i;
int limit = sqrt (double(n));
for (i = 2; i <= limit; i++)
if (n % i == 0){
next_prime (n + 1);

return;
}

is invalid. First of all you should convert n to unsigned value otherwise the code will not work.

Also you are changing n but you are not changing the loop condition.

EDIT: Oh I am sorry. I did not see that you are using a recursion. Your function does return nothing. So its using has no any sense. I think that you should write it such a way that either it will return bool or the next prime number.
Last edited on Jan 21, 2013 at 7:06pm
Jan 22, 2013 at 3:06pm
As I said ... every day I'm getting better..... final code...:)



#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;

bool isPrime(int n);
void getDivisors (int n);
void getNextPrime (int n);

int MIN_PRIME = 2;

int main()
{
int userInput;


while (true)
{
cout << "Enter a num (0 = Exit) and press ENTER: ";
cin >> userInput;

if (userInput == 0)
break;
if (isPrime (userInput))

cout << "num is prime" << endl;
else
cout << "num is not prime" << endl;

getDivisors (userInput);
cout << endl;
userInput++;

getNextPrime (userInput);

cout << endl;
}

system ("PAUSE");
return 0;
}

bool isPrime (int i_numberToCheck)
{
int limit = sqrt (double(i_numberToCheck));

for (int i = MIN_PRIME; i<= limit; i++)
{
if (i_numberToCheck % i == 0)
return false;
}

return true;
}

void getDivisors (int i_numberToCheck)
{
int sqrt_of_n = sqrt (double(i_numberToCheck));

for (int i = MIN_PRIME; i <= sqrt_of_n; i++)
{
if (i_numberToCheck % i == 0)
{
cout << i << ", ";
getDivisors (i_numberToCheck / i);

return;
}
}
cout << i_numberToCheck;
}

void getNextPrime (int i_numberToCheck)
{
int limit = sqrt (double(i_numberToCheck));

for (int i = MIN_PRIME; i <= limit; i++)
{
if (i_numberToCheck % i == 0)
{
getNextPrime (++i_numberToCheck);

return;
}
}

cout << "Next Prime: " << i_numberToCheck;
}



ps
code checks: prime or not, gives all divisors /without 1/ , gives next prime..
compiler : Microsoft Visual Studio
Last edited on Jan 22, 2013 at 3:32pm
Jan 22, 2013 at 3:55pm
Hi ,i am also a new one who just begin c++. I just wrote a code for checking a number whether prime or not..check it out..


#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
int a,b,c,d;
cout<<"Type the number :";
cin>>a;
for(b=2;b<a;b++){
c=a%b;
if(c==0){
d=0;
break;
}
}
if(d==0){
cout<<a;
cout<<" is not a Prime Number"<<endl;
}
else{
cout<<a;
cout<<" is a Prime Number"<<endl;
}
system("PAUSE");
}
Thanks...
Jan 22, 2013 at 4:19pm
@slamdon0709


I'd like to ask is 2 a prime number?
Jan 22, 2013 at 4:40pm
yes , it is.. just one even prime number..
Jan 22, 2013 at 5:15pm
sorry slamdon, but it does not work.....
Topic archived. No new replies allowed.