Sunday 23 August 2015

Recursion to sum numbers from 1 to n

Write a recursive function that computes the sum of all numbers from 1 to n, where n is given as parameter.
public class SumofNNumbers {

 public static int sum(int n){
  if( n<0)
   throw new IllegalArgumentException("Input must be a positive integer");
  return getSum(n);
 }
 
 private static int getSum(int num){
  if(num == 0)
   return 0;
  return num + getSum(--num);
 }
}


Following is the junit test case for above program.

import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class SumofNNumbersTest {

 @Test
 public void test1(){
  assertTrue(SumofNNumbers.sum(0)==0);
  assertTrue(SumofNNumbers.sum(1)==1);
  assertTrue(SumofNNumbers.sum(2)==3);
  assertTrue(SumofNNumbers.sum(3)==6);
  assertTrue(SumofNNumbers.sum(4)==10);
 }
}


No comments:

Post a Comment