Find the sum of squares 1^2 + 2^2 + ... n^2 using iteration and recursion
* I'm guessing we need to modify it
Here's the code unmodified
public class Sum {
//Non recursive sum
public static long sum1 (int n) {
long sum = 1L;
for (int i = 2; i <= n; ++i)
sum = sum + i *i ;
return sum;
}
//Recursive sum
public static long sum2 (int n) {
if (n < 2)return 1L;
return sum2(n - 1) + n * n;
}
}
public class Sum { //Non recursive sum public static long sum1(int n) { long sum = 0L; for (int i = 1; i <= n; ++i) sum = sum + i * i; return sum; } //Recursive sum public static long sum2(int n) { if (n < 1) return 0L; return sum2(n - 1) + n * n; } public static void main(String[] args) { System.out.println(sum1(10)); System.out.println(sum2(10)); } }
Get Answers For Free
Most questions answered within 1 hours.