c++ - C+中如何实现高效累加?
天蓬老师
天蓬老师 2017-04-17 13:31:55
0
6
648

蓝桥杯有这么一道题:
问题描述
求1+2+3+...+n的值。
输入格式
输入包括一个整数n。
输出格式
输出一行,包括一个整数,表示1+2+3+...+n的值。

注意事项:
说明:请注意这里的数据规模。

本题直接的想法是直接使用一个循环来累加,然而,当数据规模很大时,这种“暴力”的方法往往会导致超时。此时你需要想想其他方法。你可以试一试,如果使用1000000000作为你的程序的输入,你的程序是不是能在规定的上面规定的时限内运行出来。

如果不用for循环累加的话,还有其他什么更高效的累加方法吗?

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(6)
巴扎黑

1 + 2 + 3 + ... + n = n * (n + 1) / 2

Time complexityO(1).

洪涛

The correct answer upstairs, I think this question mainly examines: construct a data type (large integer) yourself, and then implement its four arithmetic operations, because it seems from the question that its value exceeds the range that general integers can represent.

刘奇

This is not a problem with the programming method, this is a problem with your problem-solving method.

黄舟

If the data obtained is too large, you can use an array to retain each digit and then output it

左手右手慢动作

The problem of summing arithmetic sequences! ! ! What you have to consider is how to calculate n*(n+1)/2 quickly. To start with something new, like dividing by two you can use displacement to accelerate.

小葫芦

When seeing programming questions, it is often easy to think about the problem from the perspective of computer thinking. However, for a purely computational question like this, you should be able to get a more concise answer by thinking about it from mathematical thinking.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template