如何将该迭代语句转换为递归语句?

问题描述

因此,我有一个编程项目,在该项目中,我需要创建一个确定数字是否为完美平方的程​​序,如果是,则将其写入.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进行操作。 任何帮助将不胜感激

解决方法

对于递归函数,可以使用按进制搜索算法:

 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);
}