斐波那契数列Fibonacci
斐波那契数列指的是这样一个
数列
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368
特别指出:第0项是0,第1项是第一个1。
这个数列从第2项开始,每一项都等于前两项之和。
斐波那契
数列的发明者,是意大利数学家
列昂纳多·斐波那契(Leonardo Fibonacci),生于公元1170年,卒于1250年,籍贯是
比萨。他被人称作“比萨的
列昂纳多”。1202年,他撰写了《算盘全书》(Liber Abacci)一书。他是第一个研究了印度和阿拉伯数学理论的欧洲人。他的父亲被比萨的一家商业团体聘任为外交领事,派驻地点相当于今日的
阿尔及利亚地区,列昂纳多因此得以在一个阿拉伯老师的指导下研究数学。他还曾在埃及、
叙利亚、希腊、
西西里和
普罗旺斯等地研究数学。
通过tableview 展示
斐波那契数列Fibonacci
代码如下:
.h文件
#import <UIKit/UIKit.h>
@interface ViewController : UITableViewController
@end
.m文件
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic,strong) NSArray *numberList;
@property (nonatomic,assign,getter=isDesc) BOOL desc;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self loadData:^(NSArray *numbers) {
//
self.numberList = numbers;
[self.tableView reloadData];
self.navigationItem.title = @"Fibonacci";
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"切换顺序" style:UIBarButtonItemStylePlain target:self action:@selector(sortList)];
}];
}
- (void)sortList
{
self.desc = !self.isDesc;
self.numberList = [self.numberList sortedArrayUsingComparator:^NSComparisonResult(NSNumber *obj1, NSNumber *obj2) {
//
return self.desc ? obj1.integerValue < obj2.integerValue : obj1.integerValue > obj2.integerValue;
}];
[self.tableView reloadData];
}
/// 异步加载 Fibonacci 数列
- (void)loadData:(void (^)(NSArray *numbers))finished
{
dispatch_async(dispatch_get_global_queue(0, 0), ^{
//
NSArray *array = [self fibonacci:INT8_MAX];
dispatch_sync(dispatch_get_main_queue(), ^{
//
finished(array);
});
});
}
//计算 Fibonacci 数列
- (NSArray *)fibonacci:(int)n
{
if (n<2) {
return nil;
}
NSMutableArray *arrayM = [NSMutableArray arrayWithObjects:@"0",@"1", nil];
for (int i = 2; i < n; ++i) {
long fib1 = [arrayM[i - 1] integerValue];
long fib2 = [arrayM[i - 2] integerValue];
if (fib1 + fib2 > UINT8_MAX) {
NSLog(@"%d",i);
break;
}
[arrayM addObject:@(fib1 + fib2)];
}
return arrayM;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.numberList.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
NSInteger row = indexPath.row;
if (self.isDesc) {
row = self.numberList.count - row - 1;
}
cell.textLabel.text = [NSString stringWithFormat:@"n:%zd - fib:%zd",row,[self.numberList[indexPath.row]integerValue]];
return cell;
}
@end
实现效果图: