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();
}

Dani AI

Generated

You are almost there. Two main issues in your snippet: the flag logic is inverted and never set to 1 for primes, and you print from inside the inner loop before you know whether i is prime. Sky Diploma already pointed out the = vs == bug and the need to stop after the first hit. Also, as Skeen noted, use int main() and standard headers; conio.h, clrscr(), and getch() are non‑standard. Finally, you only need to test divisors up to sqrt(i) and can skip even divisors for a big speedup.

A compact, correct approach is to split primality into a helper and walk left from n - 1 until the first prime is found.

#include <iostream>

bool is_prime(int x) {
    if (x < 2) return false;
    if ((x % 2) == 0) return x == 2;
    for (int d = 3; d * d <= x; d += 2) {
        if (x % d == 0) return false;
    }
    return true;
}

int main() {
    int n;
    std::cout << "Enter the number: ";
    if (!(std::cin >> n)) return 1;

    if (n <= 2) {
        std::cout << "No prime to the left.\n";
        return 0;
    }

    for (int i = n - 1; i >= 2; --i) {
        if (is_prime(i)) {
            std::cout << i << '\n';
            return 0;  // stop after the nearest left prime
        }
    }
    return 0;
}

Troubleshooting tips:

  • Reset any state per candidate number; do not reuse a single flag across different i unless you reinitialize it before each inner loop.
  • Keep printing and return outside the divisor loop; only act once you have a definitive result.
  • For very large inputs, consider testing only 6k ± 1 candidates and divisors to reduce iterations, but the d * d <= x check already makes this efficient for typical ranges.

Recommended Answers

All 2 Replies

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.

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":

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.