如何检查数组是否包含Fibonacci序列?

时间:2014-10-07 02:56:19

标签: ios objective-c arrays

我在下面有这个代码,我生成一个基于NSArray数字中最高数字停止的斐波纳契序列。我试图检查数字数组中的数字是否都是斐波纳契数。我如何比较数字和fibonacciArray,以便如果数字都是斐波纳契数,我的函数将返回yes或者如果数字数组中的某些数字不是斐波纳契数,则返回no?

编辑:以下是示例测试数组,如果有帮助..

 [self onlyFibonacciValues:@[@21, @2, @8, @3]];
 [self onlyFibonacciValues:@[@21, @6, @2]];


- (BOOL)onlyFibonacciValues:(NSArray *)numbers {

NSArray *newNumbers = [numbers sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"intValue" ascending:YES]]];
NSMutableArray *sortedArray = [newNumbers mutableCopy];

NSInteger firstFibonacci = 1;
NSInteger secondFibonacci = 2;

NSInteger lastObjectInArray = [sortedArray.lastObject integerValue];

NSMutableArray *fibonacciArray = [NSMutableArray new];
[fibonacciArray addObject:[NSNumber numberWithInteger:firstFibonacci]];
[fibonacciArray addObject:[NSNumber numberWithInteger:secondFibonacci]];

while (lastObjectInArray > secondFibonacci) {

    secondFibonacci = secondFibonacci + firstFibonacci;
    firstFibonacci = secondFibonacci - firstFibonacci;

    [fibonacciArray addObject:[NSNumber numberWithInteger:secondFibonacci]];

}

return YES;
}

1 个答案:

答案 0 :(得分:2)

没有必要生成全新的斐波纳契数列,以便检查当前数组的值。您需要做的就是遍历当前数组的元素,将每个元素检查到下一个Fibonacci数。你可以在一个循环中完成它:

int curr = 1, prev = 1;
for (NSNumber *n in newNumbers) { // You do not need a mutable copy of the sorted array
    int v = [n intValue];
    while (curr < v) {
        curr += prev;
        prev = curr-prev;
    }
    // At this point curr is the next Fibonacci number
    // which is greater than or equal to the current value
    // in the array. Holes and duplicates are allowed.
    if (curr != v) return NO;
}
return YES;