下面是用Objective-C語言寫的。
斐波那切數列
-(void)Fibonacci:(int)n{
int one = 1;
int two = 0;
int fibN = 0;
for(int i = 2; i <= n; ++i){
fibN = one + two;
two = one ;
one = fibN;
NSLog(@"%d",fibN);
}
}
複製程式碼
二分查詢
-(void)binarySearch:(NSArray <NSNumber *>*)a len:(int)len goal:(int)goal{
int low = 0;
int high = len - 1;
while(low <= high){
int middle = (high - low )/ 2 + low;
int m = [a[middle] intValue];
if( m == goal){
NSLog(@"找到了在第%d位",middle+1);
return;
}else if(m > goal){
high = middle - 1;
}else{
low = middle +1;
}
}
NSLog(@"沒找到");
}
複製程式碼
是否質數
方法一
-(void)isPrime_1:(int)num{
int tmp = num - 1 ;
for(int i = 2 ; i<= tmp; i++){
if(num % i == 0){
NSLog(@"不是質數");
return;
}
}
NSLog(@"是質數");
}
複製程式碼
方法二
-(void)isPrime_2:(int)num{
int tmp = sqrt(num);
for(int i = 2 ; i<= tmp; i++){
if(num % i == 0){
NSLog(@"不是質數");
return;
}
}
NSLog(@"是質數");
}
複製程式碼
是否醜數
-(void)isUgly:(int)num{
if(num == 0){
NSLog(@"不是醜數");
}else if(num == 1){
NSLog(@"是醜數");
}else{
while (num % 2 == 0) {
num /= 2;
}
while (num % 3 == 0) {
num /= 3;
}
while (num % 5 == 0) {
num /= 5;
}
if(num == 1){
NSLog(@"是醜數");
}else{
NSLog(@"不是醜數");
}
}
}
複製程式碼
是否2的冪數
-(void)isPowerOfTwo:(int)n{
if(n == 1){
NSLog(@"是2的冪");
}
if(n >= 2 && n%2 == 0){
[self isPowerOfTwo:(n/2)];
}
NSLog(@"不是2的冪");
}
複製程式碼
是否3的冪數
-(void)isPowerOfThree:(int)n{
if(n > 1){
while (n%3 == 0) {
n=n/3;
}
if(n == 1){
NSLog(@"是3的冪");
}else{
NSLog(@"不是3的冪");
}
}
}
複製程式碼
質數的個數
-(void)countPrimes:(int)n{
int count = 0;
if(n > 2){
count ++;
}
for(int i = 3; i < n ; i += 2){
if([self isPrime:i]){
count ++;
}
}
NSLog(@"有%d個質數",count);
}
-(BOOL)isPrime:(int)n{
if(n == 1){
return NO;
}
for(int i = 3 ; i <= sqrt(n); i += 2){
if( n % i == 0){
return NO;
}
}
return YES;
}
複製程式碼