Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

program to find prime number after a given number

Program to find a prime number after a given number:
I used the theory that prime numbers are divisible by only 2 numbers 1 and itself.

#include <stdio.h>
#include <conio.h>
int main(int argc, char const *argv[])
{
   int num,a=0,i,j;
   printf("Enter a number: ");
   scanf("%d",&num);
   for(i=num+1;i>0;i++){
       for(j=1;j<=i;j++){
           if(i%j==0){
              a=a+1;
           }
       }
       if(a==2){
           printf("%d",i);
           break;
       }
   }
   return 0;
}

This code is working only for a single increment like if user gives the input as 4 it is returning the output as 5. But it wont return output if input is given as 7 (it should return 11)

Then I modified the code as below :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include <stdio.h>
#include <conio.h>
void main(int argc, char const *argv[])
{
   int num,a=0,i,j;
   printf("Enter a number: ");
   scanf("%d",&num);
   for(i=num+1;i>0;i++){
        a=0;
        for(j=1;j<=i;j++){
            if(i%j==0){
               a=a+1;
            }
        }
        if(a==2){
            printf("%d",i);
            break;
        }
    }
}

This one runs well.
I am confused why the program gives the output if i declared the variable after the for loop but fails to give it if declared before?

>Solution :

Notice the a variable is not changed through the bigger for loop.

Meaning, after the first iteration we’ll have a>=2 (since every number has at least 2 divisors, while primes have precisely 2), and at the next iteration, this value does not reset.

You can try and print the value of a in every iteration from the first code snippet to make sure 🙂

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading