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

C++ prime number program help

here is my program
i think that it's right

#include<iostream.h>
int main(){
	int n,i=3;
	cout<<"please enter number to see weither it is a prime one or not"<<endl;
	cin>>n;
	if(n==2||n==3){cout<<n<<"is prime number"<<endl;}
			else if(n%2==0)
	{cout<<n<<"\t is not prime"<<endl;}
	else{
	for(i=3;i<n;i+=2)
		{	if(n%i==0)
			{cout<<n<<"\t is not a prime number"<<endl;break;}
		
	else { if (i=n-1){
		
			cout<<n<<"is a prime number"<<endl;
	}}}}
			return 0;
		
		}

plz tell me if you found any mistake on it:)

nemoo
Newbie Poster
22 posts since Nov 2007
Reputation Points: 10
Solved Threads: 0
 

Your formatting is terrible and makes it difficult to follow. Here is the same program reformatted the way it should be formatted. Note that it is very easy to spot mis-matched braces when formatted this way. Also, don't mix using tabs and spaces because they will get screwed up when you post it here.

#include<iostream>
using namespace std;

int main()
{
    int n,i=3;
    cout<<"please enter number to see weither it is a prime one or not"<<endl;
    cin>>n;
    if(n==2||n==3)
    {
       cout<<n<<"is prime number"<<endl;
    }
    else if(n%2==0)
    {
        cout<<n<<"\t is not prime"<<endl;
    }
    else
    {
        for(i=3;i<n;i+=2)
        {
            if(n%i==0)
            {
                cout<<n<<"\t is not a prime number"<<endl;break;
            }	
            else if (i=n-1)
            {	
			    cout<<n<<"is a prime number"<<endl;
            }
        }
    }
    return 0;
}
Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

Looking at AD's version above, line 25 has a common typographic error (hey, we all do this from time to time!)

Line 19 could be improved by setting the loop limit as for( i = 3; i < n/2 +1; i += 2 ) . This will save doing tests for values over half the size of the number, which obviously won't do any good.

This code continues testing past the point of proving the number not prime. You should structure the loop to end at the first instance of non-primeness. If you get all the way through the loop without proving that, then it must be prime. As written, your code creates a lot of output all repeating the not prime statement.

Val

vmanes
Posting Virtuoso
1,914 posts since Aug 2007
Reputation Points: 1,268
Solved Threads: 228
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You