码迷,mamicode.com
首页 > 其他好文 > 详细

【华为OJ】【061-等差数列】

时间:2016-05-18 19:14:31      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:

【华为OJ】【算法总篇章】


【华为OJ】【061-等差数列】

【工程下载】


题目描述

功能:等差数列 2,5,8,11,14。。。。
输入:正整数N >0
输出:求等差数列前N项和
返回:转换成功返回 0 ,非法输入与异常返回-1

输入描述

输入一个正整数。

输出描述

输出一个相加后的整数。

输入例子

2

输出例子

7

算法实现

import java.util.Scanner;

/**
 * Author: 王俊超
 * Date: 2015-12-25 16:59
 * All Rights Reserved !!!
 */
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
//        Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt"));
        while (scanner.hasNext()) {
            String input = scanner.nextLine();
            try {
                System.out.println(sum(Integer.parseInt(input)));
            } catch (Exception e) {
                System.out.println("-1");
            }
        }

        scanner.close();
    }

    private static int sum(int n) {
        return (3 * n + 1) * n / 2;
    }
}

【华为OJ】【061-等差数列】

标签:

原文地址:http://blog.csdn.net/derrantcm/article/details/51415694

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!