蓝桥杯有这么一道题:
问题描述
求1+2+3+...+n的值。
输入格式
输入包括一个整数n。
输出格式
输出一行,包括一个整数,表示1+2+3+...+n的值。
注意事项:
说明:请注意这里的数据规模。
本题直接的想法是直接使用一个循环来累加,然而,当数据规模很大时,这种“暴力”的方法往往会导致超时。此时你需要想想其他方法。你可以试一试,如果使用1000000000作为你的程序的输入,你的程序是不是能在规定的上面规定的时限内运行出来。
如果不用for循环累加的话,还有其他什么更高效的累加方法吗?
PHP中文网2017-04-17 13:33:55
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.
怪我咯2017-04-17 13:33:55
This is not a problem with the programming method, this is a problem with your problem-solving method.
黄舟2017-04-17 13:33:55
If the data obtained is too large, you can use an array to retain each digit and then output it
ringa_lee2017-04-17 13:33:55
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.
高洛峰2017-04-17 13:33:55
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.