Sunday 23 August 2015

Check for a prime number using recursion

Write a recursive program, to check whether given number is prime or not.
public class Prime {

 public static boolean isPrime(int num) {
  if(num == 2)
   return true;
  
  if (num % 2 == 0)
   return false;
  
  return primeCheck(num, 3);
 }

 private static boolean primeCheck(int num, int count) {
  if (count > Math.sqrt(num))
   return true;

  if (num % count == 0)
   return false;

  return primeCheck(num, count += 2);
 }
}


Following is the junit test case for above program.

import static org.junit.Assert.*;

import org.junit.Test;

public class PrimeTest {
 @Test
 public void test1(){
  assertTrue(Prime.isPrime(2));
  assertTrue(Prime.isPrime(3));
  assertTrue(Prime.isPrime(5));
  assertTrue(Prime.isPrime(7));
  assertTrue(Prime.isPrime(11));
  
  assertFalse(Prime.isPrime(20));
  assertFalse(Prime.isPrime(4));
  assertFalse(Prime.isPrime(25));
  assertFalse(Prime.isPrime(33));
 }
}


No comments:

Post a Comment