Tuesday, December 15, 2009

Java One Liners Collection

Today while I was going through my discrete maths notes It occurred to me that there are some algorithms that we could easily implement as just one liners. I just thought of publishing them so that they could be useful to anyone in the future. Please don't forget to comment and also add more algorithms of this style if you have. Also the last algorithm is left for you to be implemented :-).

The Following Class contains the Code 
  /**   
  *    
  * @author SHEN   
  */   
  public class OneLinerAlogrothmCollection {   
    /*   
     * One Liner Algorithm for Calculating the Corresponding Fibonachi series   
     * number for a given integer   
     */   
    public int fib(int n) {   
       {   
         return (n <= 2) ? 1 : fib(n - 1) + fib(n - 2);   
       }   
    }   
    /*   
     * One Liner Algorithm for Calculating the Corresponing Factorial for a   
     * Given Integer   
     */   
    public int fact(int n) {   
       return (n <= 1) ? 1 : fact(n - 1) * n;   
    }   
    /*   
     * One Liner Algorithm for Determining if a given Number is a Perfect Square   
     * or not   
     */   
    public boolean isPerfectSquare(int n) {   
       return (n > 1) ? (n & (n - 1)) == 0 : false;   
    }   
    /*   
     * One Liner Algorithm for Determining if a Given integer is a odd or a even   
     * integer returns : true -> for even integers false -> for odd integers   
     */   
    public boolean isEven(int n) {   
       return (n & 1) == 0;   
    }   
    /*   
     * One Liner Algorithm for Determining if a Given Integer is a Prime Number   
     * returns : true -> for prime integers false -> for others   
     */   
    public boolean isPrime(int input) {   
       throw new UnsupportedOperationException("It's Up to You to Implement this");   
    }   
  }   

No comments: