zl程序教程

您现在的位置是:首页 >  其它

当前栏目

sieve的objective-c实现

实现 Objective
2023-09-14 08:56:51 时间

用obj-cl来实现前面的sieve代码貌似“丑”了不少,应该有更好的方式:比如不用Foundation或不用NSArray类,而改用其它更“底层”的类。
先把代码贴出来:

//

// main.m

// sieve

// Created by kinds on 15/5/2.

// Copyright (c) 2015年 hopy. All rights reserved.

#import Foundation/Foundation.h 

//#include time.h 

//#include unistd.h 

typedef unsigned long long ULL;

void zero_array(ULL count,NSMutableArray *ary){

 for (ULL i = 0; i count; i++) {

 [ary addObject:[NSNumber numberWithInt:0]];

ULL sieve_objc(ULL n){

 NSMutableArray *ary = [NSMutableArray arrayWithCapacity:n+1];

 zero_array(n+1, ary);

 //NSLog(@"ary is %lu",[ary count]);

 ULL max = sqrtl(n);

 ULL p = 2;

 NSNumber *x = nil;

 while (p =max) {

 for(ULL i=2*p;i i+=p)

 //[ary replaceObjectAtIndex:i withObject:[NSNumber numberWithInt:1]];

 [ary setObject:[NSNumber numberWithInt:1] atIndexedSubscript:i];

 x = [ary objectAtIndex:++p];

 while ([x intValue]) {

 x = [ary objectAtIndex:++p];

 x = [ary objectAtIndex:n];

 while ([x intValue]) {

 n--;

 x = [ary objectAtIndex:n];

 return n;

ULL sieve(ULL n){

 char *ary = malloc(n+1);

 if(!ary) return 0;

 memset(ary,0,n+1);

 ULL max = sqrtl(n);

 ULL p = 2;

 while (p = max) {

 for(ULL i = 2*p;i i+=p)

 ary[i] = 1;

 while (ary[++p]); //empty

 while(ary[n]) n--;

 return n;


if([args count] != 2){ printf("usage : %s n\n",[[[args objectAtIndex:0] lastPathComponent] UTF8String]); return 1; long long n = [[args objectAtIndex:1] integerValue]; if (!n) { puts("you must input a number"); return 2; if(n 0){ puts("you must input a +number"); return 3; clock_t start = clock(); //ULL result = sieve((ULL)n); ULL result = sieve_objc((ULL)n); if(!result){ puts("sieve calc failed!"); return 4; double end = ((1.0 * (clock() - start)) / CLOCKS_PER_SEC) * 1000.0; printf("max p is %llu (take %f ms)\n",result,end); return 0; }

没找到NSArray中的类或实例方法有可以完成如下简单的数组功能:


所以写了一个zero_array函数来完成该功能,该函数超慢的。
所以可想而知这个obj-c版的效率能有多差,等有机会再优化一下吧。


深入Objective-C Runtime机制(一):类和对象的实现 1.概要      对于Runtime系统,相信大部分iOS开发工程师都有着或多或少的了解。对于Objective-C,Runtime系统是至关重要的,可以说是Runtime系统让Objective-C成为了区分于C语言,C++之外的一门独立开发语言,让OC在拥有了自己的面向对象的特性以及消息发送机制。并且因为其强大的消息发送机制,也让很多人认为Object
因为 ObjC 的 runtime 只能在 Mac OS 下才能编译,所以文章中的代码都是在 Mac OS,也就是 x86_64 架构下运行的,对于在 arm64 中运行的代码会特别说明。