我有下面的系列,无限长。
1 2 4 7 11 16 22 29 37.....
我需要找到一个给定的数字(比如,n)它是否存在于这个系列中,或者不是。这个数字可以再输入任意次数,也不奇怪,一个很长的值。
考虑到这个系列是无限的,我认为创建一个数据结构来存储元素是无关紧要的(我是不是太笨了?)
仔细观察这个系列,我发现连续项之间的差异形成了一个算术级数。
1 2 3 4 5 6 7 8.....
所以,一个最简单的方法是从1开始继续添加它们,如果我们达到了==N,则输出Yes,否则,如果>N,则不。
但这将是我能想到的最昂贵的算法。
我一定漏掉了一些非常敏锐的逻辑,但不确定。
最佳答案
According to this series,T((n)-N'th number in series.
T(1) = 1
T(2) - T(1) = 1
T(3) - T(2) = 2
T(4) - T(3) = 3
.
.
.
T(n) - T(n - 1) = n - 1
//sum of all above
T(n) - T(1) = 1 + 2 + 3 + 4 + 5 + ... + (n - 2) + (n - 1)
//T(1) = 1
T(n) - 1 = n(n - 1) / 2
2 * (T(n) - 1) = n^2 - n
//T(n) is your input number and check whether n has an integer
//solutions in following quadratic equation, if yes T(n) is in this series.
n^2 - n - 2 * (number - 1) = 0;
simply check if the value of " (1 + sqrt((8.0 * number) - 7)) / 2.0 " is integer.
Checking if float is an integer
关于c - C-在很长的序列中找到数字的最佳技巧是什么,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27683546/