顯示具有 演算法 標籤的文章。 顯示所有文章
顯示具有 演算法 標籤的文章。 顯示所有文章

2012年12月4日 星期二

求最大公因數的演算法


西元前 300 年,由歐幾里德 (Euclid) 提出:

1. 尋求兩個正整數 u 和 v 的最大公因數
2. 若 v = 0,則完成計算,u 為最大公因數
3. 計算 temp = u%v,u = v,v = temp, 並回到 2.

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        
        unsigned int u, v, temp ;
        
        NSLog(@"Please type in two nonnegative integers.");
        scanf(" %u %u", &u, &v);
        
        while (v!=0) {
            temp = u%v;
            u = v;
            v = temp;
        }
        
        NSLog(@"Their greatest common divisor is %u", u);
    }
    return 0;
}