在算术进程中缺少术语 [英] missing term in Arithmetic Progression
本文介绍了在算术进程中缺少术语的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请提供一个算法或代码,以便在c#中的算术级数中找到一个缺失的术语。
Ex:
1.输入:1,11,31,41 ,51
输出:21
2.输入:1,3,5,7,11
输出:9
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
推荐答案
这可能应涵盖所有类型的测试用例。
This probably should cover all kinds of test cases.
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;
}
}
}
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;
}
这篇关于在算术进程中缺少术语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文