This blog is under construction

Sunday 21 July 2013

C program to check prime number or not using recursion

Write a C program to check prime number or not using recursion.


  #include <stdio.h>

  /* checking whether the given number is prime or not */
  void checkPrime(int num, int div) {
        /*
         * if div equals to num/2, then no number from
         * 2 to n/2 perfectly divides the given input
         */
        if (div == (num / 2)) {
                printf("%d is prime\n", num);
                return;
        }

        if ((div != 1) && (num == 1 || num % div == 0)) {
                printf("%d is not a prime number\n", num);
                return;
        }

        /* recursive call */
        checkPrime(num, ++div);
        return;
  }

  int main() {
        int num, div = 1;

        /* get the input value from the user */
        printf("Enter your input value:");
        scanf("%d", &num);

        /* checks whether the given input is prime or not */
        checkPrime(num, div);

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input value:123
  123 is not a prime number
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input value:151
  151 is prime


No comments:

Post a Comment