算法02-求1-n的和高级求法

题目要求:
不能使用for while 等循环语句; if() else; switch case;等系列判断语句
示例 1

输入
3
输出
6

思路1:
利用高斯定理:等差数列求和(sum = (首项+末项)*项数/2)

public class Test {
  public int sumNumber(int n){
    return (int)(1+n)*n/2;
  }
  public static void main(String[] args) {
    Test test = new Test();
    System.out.println("input a number");
    Scanner scanner = new Scanner(System.in);
    test.sumNumber(scanner.nextInt());
  }
}

思路2
利用递归和短路与的特点进行计算

public int sumNumber(int n){
    //return (int)(1+n)*n/2;
    int sum = n;
    //后面的sum+=sumNumber()递归调用的只可能是正数,当n=0时候不满足条件了,逐层进行调用得到结果
    boolean flag = n>0 && (sum+=sumNumber(n-1))>0;
    return sum;
  }

这就是主要的两种思路,有其他好方法的伙伴可以在评论区留言


转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 1371769065@qq.com

文章标题:算法02-求1-n的和高级求法

字数:211

本文作者:一叶知秋

发布时间:2020-07-04, 15:39:11

最后更新:2020-07-04, 15:40:57

原始链接:http://yoursite.com/2020/07/04/arithmtic/02/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

×

喜欢就点赞,疼爱就打赏

相册 github