2017-06-26 80 views
0

我正在做一個賦值,我必須創建一個讀取兩個數組(x_vals [i]和y_vals [i])的迭代函數和遞歸函數,並分別打印出GCD。遞歸函數和迭代函數的結果應該是相同的,否則一個或兩個函數都會出錯。以下是我的。我無法理解的是程序有什麼問題,比如爲什麼我的結果不匹配。GCD,迭代和遞歸問題

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 

/* function prototypes */ 
int iterGCD(int x, int y); 
int recGCD(int x, int y); 

int main(int argc, char *argv[]) 
{ 
    int num_vals = 6; 
    int x_vals[] = {3, 9, 12, 36, 1, 105}; 
    int y_vals[] = {3, 21, 18, 27, 12, 91}; 
    int i = 0; 

    printf("Assignment 2 Problem 2 by <Jonathan Taylor>.\n\n"); 

    while (i<num_vals) 
    { 
     printf("Iterative GCD: x = %d, y = %d, result = %d\n", x_vals[i], y_vals[i], iterGCD(x_vals[i],y_vals[i])); 
     printf("Recursive GCD: x = %d, y = %d, result = %d\n\n", x_vals[i], y_vals[i], recGCD(x_vals[i],y_vals[i])); 

     i++; 
    } 

    return 0; 
} 

int iterGCD(int x, int y) 
{ 
    int GCD = 1; 
    int number = 1; 

    /*For loop method, you could ignore if you like 
    for (number = 1; number <= x && number <= y; ++number){ 
     if(x % number == 0 && y % number == 0){ 
     GCD = number; 
    } 
    */ 

    while ((number <= x) && (number <= y)) { 
     ++number; 

     if(x % number == 0 && y % number == 0) { 
     GCD = number; 
     } 

     return GCD; 
    } 
} 

int recGCD(int x, int y) 
{ 
    if(y != 0){ 
     int remainder = x % y; 
     return recGCD(y, remainder); 
    } 
    return x; 
} 
+0

爲什麼你認爲什麼是錯的? –

+0

你的結果是? – MrJLP

+0

顯示每個結果,以及期望的結果 – MrJLP

回答

1

你在iterGCD回報是放錯了地方:

while ((number <= x) && (number <= y)) { 
    ++number; 

    if(x % number == 0 && y % number == 0) { 
    GCD = number; 
    } 

    return GCD;  // <----------- wrong 
} 

你去通過循環和return的單次迭代的循環結束。移動return後循環:

while ((number <= x) && (number <= y)) { 
    ++number; 

    if(x % number == 0 && y % number == 0) { 
    GCD = number; 
    } 

} 
return GCD; // <----------- move here 
+0

就這麼簡單,非常感謝! –

+0

@EliTaylor很高興能幫到你。如果您覺得它有用,請隨時[接受此答案](https://stackoverflow.com/help/accepted-answer)。 – dbush