黑马程序员技术交流社区
标题:
关于求平方和的,递归的写法!请高手赐教
[打印本页]
作者:
幸福相随
时间:
2014-3-9 10:26
标题:
关于求平方和的,递归的写法!请高手赐教
class Demo
{
public static void main(String[] args)
{
//计算1*1+2*2+3*3+...n*n
System.out.println(count(100));
}
public static int count(int n){
return n == 1 ? 1 : count(n-1) + n * n;//使用了递归,
}
}
就是关于求平方和的,理解不是很透彻,希望高手赐教!
作者:
optimisticpig
时间:
2014-3-9 11:05
class Demo
{
public static void main(String[] args)
{
int sum =getSum(4);
System.out.println(sum);
}
public static int getSum(int n)
{
int s = 0;
for(int i=0;i<=n;i++)
{
s = s + i*i;
}
return s;
}
}
作者:
Sage
时间:
2014-3-9 12:25
class Demo {
public static void main(String[] args) {
// 计算1*1+2*2+3*3+...n*n
System.out.println(count(100));
}
/*
* 需求是计算出1*1+2*2+3*3+...n*n之和 return语句是三元表达式
* 可以理解为:
* if (n == 1){
* return 1;
* } else {
* return count(n - 1) + n * n;
* }
* 这里是用了递归算法,不断重复n * n的运算
* 根据传入的n = 100 ,count(n - 1) + n * n即100 * 100 + 99 * 99;
* 每次传入的值不断-1 , 直到1为止 ,因1 * 1 ==1 ,则return 出 它们的和
*/
public static int count(int n) {
return n == 1 ? 1 : count(n - 1) + n * n;
}
}
复制代码
作者:
天凌蓝
时间:
2014-3-9 12:39
public static int count(int n){
return n == 1 ? 1 : count(n-1) + n * n;//使用了递归,
}
这句其实可以这样理解:
public static int count(int n){
if(n==1)
return n =1 ;
return n * n+count(n-1) ;
}
作者:
osully
时间:
2014-3-9 13:04
递归 其实就是函数调用自己
理解这个很简单,只要代入几个值 验证一下 就可以发现规律 或者理解了!
比如说 你先设置n为3
函数为
public static int count(3)
{
return n == 1 ? 1 : count(3-1) + 3 * 3; //这里的count(3-1) 即 又调用了 count(2)
}
public static int count(2)
{
return n == 1 ? 1 : count(2-1) + 2 * 2; //这里的count(2-1) 即 又调用了 count(1)
}
public static int count(1)
{
return n == 1 ? 1 : count(2-1) + 2 * 2; //这里当n=1时 return 1;
}
再总结
count(3) return 的是 count(2)+3*3
count(2) return 的是 count(1)+2*2
count(1) return 的是 1
故 count(3) return 1+2*2+3*3 ;
但是递归要注意递归的次数。尽量避免内存溢出。(递归次数太多的话会造成调用函数太多)
作者:
pifuhanshu
时间:
2014-3-9 18:30
return n == 1 ? 1 : count(n-1) + n * n;的意思是:如果n=1返回n=1 如果n!=1返回count(n-1) + n * n
作者:
chaos
时间:
2014-3-9 18:55
求n的平方和就是n*n+(n-1)*(n-1)+(n-2)*(n-2)....2*2+1*1
作者:
pifuhanshu
时间:
2014-3-11 13:04
class Demo
{
public static void main(String[] args) //这句话就不用讲了:主函数
{
//计算1*1+2*2+3*3+...n*n
System.out.println(count(100));//输出递归调用后的函数值
}
public static int count(int n){
return n == 1 ? 1 : count(n-1) + n * n;//使用了递归,当n=1时,返回n=1.否则调用count(n-1)+n*n的值。这样递归调用得出1*1+2*2+。。。+n*n的值。
}
}
作者:
syw02014
时间:
2014-3-11 14:40
n == 1 ? 1 : count(n-1) + n * n;//使用了递归,
改成非递归:
int sum=0;
for(int i=1;i<=n;i++)
sum+=i*i;
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2