2014年6月14日 星期六

d013

#include
#include
#include

int main(void) {
    char s[999];
    unsigned long int store[100];
    int num;
    int i;
    while( gets(s)!=0 ) {
        memset(store, 0, 100);
        num = atoi(s);
        store[0]=1;
        store[1]=1;
        for (i=2; i
            store[i] = store[i-2]+store[i-1];
        }
        printf("%lu\n",store[num-1]);
    }
    return 0;

}

tip:
1.當數字太大時的儲存與表示方法
http://stackoverflow.com/questions/3209909/how-to-printf-unsigned-long-in-c

d039

#include
#include
#include

int main(void) {
    char s[999];
    int num;
    int i;
    while( gets(s)!=0 ) {
        num = atoi(s);
        for (i=2; i<=sqrt(num); i++) {
            if(num % i == 0){
                printf("not prime\n");
                break;
            }
        }
        if (i>sqrt(num)) {
           printf("prime\n");
        }
    }
    return 0;

}

d012

#include
#include

int main(void) {
    char s[999];
    char s2[999];
    int stelen;
    int i;
    int count;
    while( gets(s)!=0 ) {
        count = 0;
        memset(s2, 0, 999);
        stelen = strlen(s);
        for (i=stelen-1; i>=0; i--) {
            s2[count] = s[i];
            count++;
        }
        if(!strcmp(s,s2)){
            printf("Yes\n");
        }else printf("No\n");
    }
    return 0;

}

tips:
1.單純結合d001與d011
2.ISO C90 forbids mixed declarations and code 變數不要宣告在太後面的地方,最好在邏輯之前。
3.一樣記得同樣的char array你在去宣告一次並不會變成新的array,要重複使用就要用memset去empty array。

d011

#include
#include
int main(void) {
    char s[999];
    int stelen = 0;
    int spacenum;
    int i = 0;
    while( gets(s)!=0 ) {
        char s1[100];
        char s2[100];
        memset(s1, 0, 100);
        memset(s2, 0, 100);
        stelen = strlen(s);
        spacenum = strcspn(s, " ");
        for (i=0; i
            s1[i] = s[i];
        }
        for (i=spacenum+1; i
            s2[i-(spacenum+1)] = s[i];
        }
        if(!strcmp(s1,s2)){
            printf("Yes\n");
        }else printf("No\n");
    }
    return 0;

}

tips:
1.記得輸出要換行...\n
2.記得char array每次都要重新清空,就算char宣告放在while裡也一樣,不會像其他語言這樣可以重新init,在c可使用memset重設值。

source:
memset 設定位元組中的位元值,設定的方式從s 開始將n 個位元組設定成為c 的位元值並回傳s,經常運用的範圍是在將位元組的位元值清為0。
http://stackoverflow.com/questions/1559487/how-to-empty-a-char-array

d001

#include
#include
int main(void) {
    char s[999];
    int stelen = 0;
    int i = 0;
    while( gets(s)!=0 ) {
        stelen = strlen(s);
        for (i=stelen-1; i>=0; i--) {
            if(i!=0)printf("%c", s[i]);
            else printf("%c\n", s[i]);
        }
    }
    return 0;

}

tips:
1.for loop裡面不能宣告變數(ex: int i),似乎與c99有關
2.不能用scanf,測資裡有space,scant讀到space就讀完了。所以用gets。
3.scanf()讀取結尾是回傳EOF;gets()則是回傳0。