Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
1.50/5 (7 votes)
See more:
Please provide me an algorithm or code to find a missing term in Arithmetic Progression in c#.
Ex:
1. Input: 1,11,31,41,51
Output: 21

2. Input : 1,3,5,7,11
Output :9
Posted
Updated 28-Aug-14 6:03am
v2
Comments
Zoltán Zörgő 11-Nov-13 8:57am    
Homework :(
ZurdoDev 28-Aug-14 13:45pm    
Where are you stuck?

This probably should cover all kinds of test cases.

C#
public class Program
    {
        public static void Main(string[] args)
        {
            //your input
            int[] inputArray = new int[] { 1, 11, 31, 41, 61 };
            int difference = 0;
            for (int i = 0; i < (inputArray.Length - 1); i++)
            {
                int first = inputArray[i];
                int second = inputArray[i + 1];
                //find minimum difference of all terms
                if (difference == 0)
                {
                    difference = second - first;
                }
                else
                {
                    difference = Math.Min(difference, (second - first));
                }
            }
            WriteMissingElement(difference, inputArray);
            Console.ReadKey();
        }

        private static void WriteMissingElement(int reqdDifference, int[] input)
        {
            int last = input.Last();
            int nextNumber = input.First() + reqdDifference;

            while (nextNumber != last)
            {
                if (!input.Contains(nextNumber))
                {
                    Console.WriteLine(nextNumber);
                }
                nextNumber = nextNumber + reqdDifference;
            }
        }
    }
 
Share this answer
 
v3
C#
public static int GetArithmaticProgression(int[] nums)
{
    // Arithmatic Progression (AP)-
    // Example 1: 5 13 17 21 25; Missing AP is 9 between 5 and 13 with common difference 4
    // Example 2: 9 14 24 29 34; Missing AP is 19 between 14 and 24 with common difference 5
    // Example 3: 25 28 31 37 40 43: Missing AP is 34 between 31 and 37 with common difference 3
    // Namira
    int[] iDiff = new int[nums.Length - 1];

    for (int k = 0; k < nums.Length; k++)
    {
        // Which 2 numbers have the largest differnce?
        if (k > 0)
            iDiff[k - 1] = nums[k] - nums[k - 1]; // 13 - 5 (8) 17 - 13 (4)
    }

    int min = iDiff.Min(); // This is the common differnce
    int max = iDiff.Max(); // This is the largest difference between numbers.

    // Get the index of 1st number with the missing AP
    var indexAtMax = iDiff.ToList().IndexOf(max);

    // Missing number is:
    return nums[indexAtMax] + min;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900