Thursday, 11 September 2014

General Algorithms

  1. Given an array of n numbers having elements from 1 to n with one number missing. Find the missing number                                                                                                                    Algorithm 1
    1. Get the sum of numbers 
           total = n*(n+1)/2
    2  Subtract all the numbers from sum and
       you will get the missing number.
     
    Algorithm 2 
    1) XOR all the array elements, let the result of XOR be X1.
    2) XOR all numbers from 1 to n, let XOR be X2.
    3) XOR of X1 and X2 gives the missing number. 
     
  2. Euclid’s Algorithm                                                            int GCD(int A, int B) { if(B==0) return A;                                                           else return GCD(B, A % B); }                                                                                                                                       

No comments:

Post a Comment