簡體   English   中英

如何將此迭代語句轉換為遞歸語句?

[英]How can I convert this iterative statement into a recursive statement?

所以我有這個編程項目,我需要在其中創建一個程序來確定一個數字是否是一個完美的平方,如果是,則將其寫入一個 .txt 文檔。 這對於 for 循環來說非常容易和有效,但是,賦值指令說程序應該使用遞歸來完成這個。 這是我想出的迭代語句:

double division;
        for (int i = 0; i < inputs.size(); i++) {
            division = (Math.sqrt(inputs.get(i)));
            if (division == (int)division) {
                pw.println(inputs.get(i));
                 }
            }

其中, inputs是通過讀取用戶輸入創建的 ArrayList。 這解決了問題,但就像我說的,它需要是一個遞歸語句。 我知道對於遞歸,我需要一個最終會使方法停止調用自身的基本情況,但我無法弄清楚基本情況是什么。 此外,我已經看到了幾個從迭代轉換為遞歸的示例,但所有這些示例都使用單個int變量,在我的情況下,我需要使用 ArrayList 來完成。 任何幫助將不勝感激

對於遞歸函數,您可以使用 bynary 搜索算法:

 int checkPerfectSquare(long N,  
                              long start, 
                              long last) 
{ 
    // Find the mid value 
    // from start and last 
    long mid = (start + last) / 2; 
  
    if (start > last) 
    { 
        return -1; 
    } 
  
    // Check if we got the number which 
    // is square root of the perfect 
    // square number N 
    if (mid * mid == N) 
    { 
        return (int)mid; 
    } 
  
    // If the square(mid) is greater than N 
    // it means only lower values then mid 
    // will be possibly the square root of N 
    else if (mid * mid > N) 
    { 
        return checkPerfectSquare(N, start,  
                                  mid - 1); 
    } 
  
    // If the square(mid) is less than N 
    // it means only higher values then mid 
    // will be possibly the square root of N 
    else 
    { 
        return checkPerfectSquare(N, mid + 1,  
                                  last); 
    } 
} 

您可以使用平方數是奇數之和的事實。 例如

1+3 = 4 = 2^2

1+3+5 = 9 = 3^2

1+3+5+7 = 16 = 4^2,以此類推

public static void main(String[] args) {
    for (int i = 1; i < 1000; i++) {
      if (isSquare(i)) System.out.println(i);     
    }
  }
  public static boolean isSquare(int n) {
    if (n==0 || n==1) return true;
    return isSquare(n,1,1);
  }

  private static boolean isSquare(int n, int sum, int odd) {
    if (n==sum) return true;
    if (n < sum) return false;
    odd += 2;
    sum += odd;
    return isSquare(n, sum, odd);
  }

輸出:

1
4
9
16
25
36
49
64
81
100
121
144
169
196
225
256
289
324
361
400
441
484
529
576
625
676
729
784
841
900
961

您可以遞歸檢查任何較小 int 的平方是否等於您的輸入。

public static boolean isSquare(int n) {
  if (n==0 || n==1) return true;
  return isSquare(n, 1);
}

private static boolean isSquare(int n, int i) {
  if (i*i == n) return true;
  if (i*i > n) return false;
  return isSquare(n,i+1);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM