sieve的objective-c实现

用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<=n;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<=n;i+=p)
            ary[i] = 1;
        while (ary[++p]); //empty
    }
    while(ary[n]) n--;
    return n;
}


int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSProcessInfo *psi = [NSProcessInfo processInfo];
        NSArray *args = [psi arguments];
        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中的类或实例方法有可以完成如下简单的数组功能:

//定义10000个指定对象的数组
typedef struct _st_foo{
    char name[256];
    char note[1024];
    int age;
    unsigned long long id;
    }st_foo,*pst_foo;

st_foo ary[1024]; //NSArray can't do this

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

你可能感兴趣的:(素数,NSArray,obj-c,sieve)