C Language | Prime Numbers

Thursday 6 December 2012

In numbers, there are those that can be divided with different other integers and those that are only limited to the integer itself and number one (1). That kind of numbers are known as the Prime Numbers. Prime numbers can only be divided by the number one (1) or the prime number itself.

Sometimes, it can be difficult for us to recognize prime numbers specially when the numbers are large. That's why I made a program that evaluates a number and tells us if the number is a prime number or not. In this program, I used looping statements and If else statements to make the program more stable. Check out the sample code below.

     1:  
   2:  #include<stdio.h>
   3:  #include<conio.h>
   4:   
   5:  main()
   6:  {
   7:        int input, num=0, div, count, count2,x;
   8:        printf("Enter how many counts: ");
   9:        scanf("%d",&count);
  10:        
  11:        if(count>3000){
  12:        printf("You have exceeded the maximum input of 3000");
  13:        getch();
  14:        return 0;
  15:        }
  16:        
  17:        for (x=1; x<=count; x++)
  18:        {
  19:        div=0;
  20:        
  21:        printf("\nEnter Numbers: ");
  22:        scanf("%d", &num);
  23:       
  24:        if(num<=0 || num >50000)
  25:        {
  26:        return 0;
  27:        } 
  28:        for (count2 = 1; count2 <= num; count2++)
  29:        {
  30:        if(count2>0)
  31:        {
  32:        if(num%count2==0){
  33:        div++;
  34:        }}}
  35:        
  36:        if (div==2)
  37:      {printf("Prime\n");
  38:      }
  39:      else
  40:       printf("Not Prime\n");
  41:        }
  42:        
  43:        
  44:        getch();
  45:  }


The program operates like this. When run, it will ask the user how many inputs he would like to enter then the user's input will be stored in the variable named count. Count is only limited to 3000, if count will exceed 3000 the program will automatically terminate. If not, the program will proceed to asking the user to input the numbers he want to evaluate. Then, the inputs will go through the equations in evaluating the number  under the looping statements and if else statements. If the evaluated number is prime the program will print the result prime, if not the program will print not prime. After that, you can now terminate the program. You can check out the sample output below.



Hope you find this program helpful. Thanks!

No comments:

Post a Comment

Please do leave a comment. It's gonna be a friendly conversation between programmers. Hope you do find our blog helpful. Thank you!

Related Posts Plugin for WordPress, Blogger...