Thursday, 5 December 2013

Finding the missing term of an A.P.

An Arithmetic Progression is defined as one in which there is a constant difference between the consecutive terms of a given series of numbers. You are provided with consecutive elements of an Arithmetic Progression. There is however one hitch: Exactly one term from the original series is missing from the set of numbers which have been given to you. The rest of the given series is the same as the original AP.  Find the missing term.


#include <stdio.h>
int main() {
    unsigned int N,i;
    N = 0;
    int *M;
    scanf("%u",&N);
    M = (int*)malloc(sizeof(int)*N);
    for(i = 0; i<N; i++)
    {
        scanf("%d",&M[i]);
    }
    int diff1 = 0, diff2 = 0, diff3 = 0;
    diff1 = M[1] - M[0];
    diff2 = M[2] - M[1];
  
    int cd = 0;
    if (diff1 > diff2)
        cd = diff2;
    else
        cd = diff1;
   
    for(i = 0;i<N-1;i++)
    {
        if(M[i+1] - M[i] == cd)
            continue;
        else if(M[i+1] - M[i] == cd*2)
        {
            printf("%d",M[i]+cd);
        }
           
    }
       
    return 0;
}

Any question? Please mail on 27it08@gmail.com

0 comments

 
© 2011-2012 ProgrammingBlue
Posts RSS Comments RSS
Back to top