ACM 競賽題: The 3n + 1 problem

高等 C 語言

簡介

字串

指標與陣列

函數

結構

物件導向

記憶體

檔案

錯誤處理

巨集處理

C 與組合語言

資料結構

動態字串

動態陣列

鏈結串列

雜湊表

開發環境

Make

Cygwin

MinGW

DevC++

wxDevC++

編譯器

gcc 編譯器

TinyCC 編譯器

LCC 編譯器

應用主題

CGI 程式

GNU 程式

視窗程式

影像處理

練習題

訊息

相關網站

參考文獻

最新修改

簡體版

English

ACM 競賽題: The 3n + 1 problem

執行結果

D:\c>gcc nij.c -o nij

D:\c>nij
22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 len = 16
1 len = 1
2 1 len = 2
3 10 5 16 8 4 2 1 len = 8
4 2 1 len = 3
5 16 8 4 2 1 len = 6
6 3 10 5 16 8 4 2 1 len = 9
7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 len = 17
8 4 2 1 len = 4
9 28 14 7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 len = 20
10 5 16 8 4 2 1 len = 7
fij(1,10)=20

程式碼:fij.c

int main() {
    f(22);
    printf("fij(1,10)=%d", fij(1,10));
}

int f(x) {
    int n = x;
    int len = 1;
    printf("%d ", n);
    while (n != 1) {
        if (n%2==1) 
            n=3*n+1;
        else
            n=n/2;
        printf("%d ", n);
        len ++;
    }
    printf("len = %d\n", len);
    return len;
}

int fij(int i, int j) {
    int lmax = 0;
    int k;
    for (k=i; k<=j; k++) {
        int len = f(k);
        if (len > lmax) lmax = len;
    }
    return lmax;
}

Facebook

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License