iOS 实现判断一个数组是不是斐波那契数

2017-07-26  本文已影响0人  330b92bcaf74
- (void)viewDidLoad {
    [super viewDidLoad];
    NSArray *arr = @[@"8", @"2", @"4", @"6"];
    NSLog(@"======%d",[self isPeiBoWithArray:arr]);
   }

- (BOOL)isPeiBoWithArray:(NSArray *)arr {
    
    BOOL nm = YES;
    
    for (int i = 0; i < arr.count - 2; i++) {
        
        if ([arr[i] integerValue] + [arr[i + 1] integerValue] != [arr[i + 2] integerValue]) {
            
            nm = NO;
            break;
            
        }
        if (i == arr.count || [arr[i] integerValue] + [arr[i + 1] integerValue] == [arr[i + 2] integerValue]) {
            
            nm = YES;
           
        }
        
    }

    BOOL isP = NO;
    for (int i = 0; i < arr.count; i++ ) {
        
        isP = [self ispeiboWith:[arr[i] intValue]];
        
        NSLog(@"数子是不是%d", isP);
        if (isP == NO) {
            
            break;
        }
    }

    if (nm && isP) {
        
        return YES;
        
    }else {
        
        return NO;
    }
    
}

- (BOOL)ispeiboWith:(int)t {
    
    int i = 0;
    BOOL nm = YES;
    
    for (i = 1; [self fib:i] <= t; i++) {
        
        if ([self fib:i] == t) {
            nm = YES;
        }else {
            nm = NO;
        }
    }

    return nm;
}

- (int)fib:(int)n {
    
    if (n == 1 || n == 2) {
        return 1;
    }else {
        return [self fib:n - 1] + [self fib:n - 2];
    }
}

上一篇下一篇

猜你喜欢

热点阅读