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

C++ program for finding nearest prime to the left

I am trying to write a program to find nearest prime to a number to its left...using for loop
i just don't seem to get it right

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int n1,flag=0;
cout<<"Enter The Number"<<endl;
cin>>n1;
for(int i=n1;i>0;i--)
{
for(int j=2;j<(i/2);j++)
{
if(i%j==0)
{
flag=0;
}
else if(flag=1)
{
cout<<i<<endl;
}
}
}
getch();
}
ziyakhan10
Newbie Poster
5 posts since Dec 2009
Reputation Points: 10
Solved Threads: 0
 
if(flag=1)
{
cout<<i<<endl;
}

You seem to be assigning 1 to flag but not checking.

if(flag==1)
{
cout<<i<<endl;
}


Secondly, Because you only need to find one prime number. return 0; after the cout statement, would stop it.

This is the syntactical part. I would not tend to give the answer away. But would give down the algorithm.
Checking Prime Numbers

1. Set flag to 0.
2. for i runs from 2 to n.
3. check if n divided by i gives out 0.
4. If yes, set flag to 1 and break.
5. in the outer loop check if flag == 0
6. If yes, print the number is prime. and return.
7. Else do nothing.

Sky Diploma
Practically a Posting Shark
865 posts since Mar 2008
Reputation Points: 673
Solved Threads: 131
 

I am trying to write a program to find nearest prime to a number to its left...using for loop i just don't seem to get it right

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int n1,flag=0;
cout<<"Enter The Number"<<endl;
cin>>n1;
for(int i=n1;i>0;i--)
{
for(int j=2;j<(i/2);j++)
{
if(i%j==0)
{
flag=0;
}
else if(flag=1)
{
cout<<i<<endl;
}
}
}
getch();
}


^^first of all, stick to "INT MAIN()" instead of void main, besides, try using logically named variables and incprporation what Sky said, and you'll have something like this:

#include<iostream>
#include<conio.h>
using namespace std;

int main()
   {
   int SeachNumber=0, TestNumber=1, ModuloNumber=0;
   bool IsPrime=1;

   cout << "Enter The Number" << endl;
   cin >> SeachNumber;
   
   for (int a=1; a<SeachNumber; a++)
      {
      TestNumber++;
      IsPrime=true;
      for (ModuloNumber=2; ModuloNumber<TestNumber; ModuloNumber++)
          {if ((TestNumber%ModuloNumber)==0){IsPrime=false;}} 
      
      if(IsPrime==true)
          {
          cout << a << ". " << "Prime:\t"<< TestNumber << endl; 
          }
        }
   system("PAUSE");
   }

However, if you're interrested in finding like, prime numbers above 100mil, try incorporating "The Sieve of Eratosthenes": http://upload.wikimedia.org/wikipedia/commons/c/c8/Animation_Sieve_of_Eratosth-2.gif

Skeen
Junior Poster in Training
77 posts since Nov 2009
Reputation Points: 10
Solved Threads: 2
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You