History repeat itself 解题

【题目描述】

Description
angered Professor Lee who is in charge of the course. Therefore, Professor Lee decided to let Tom face a hard probability problem, and announced that if he fail to slove the problem there would be no way for Tom to pass the final exam.
As a result , Tom passed.
History repeat itself. You, the bad boy, also angered the Professor Lee when September Ends. You have to faced the problem too.
The problem comes that You must find the N-th positive non-square number M and printed it. And that’s for normal bad student, such as Tom. But the real bad student has to calculate the formula below.
Mi=1i
So, that you can really understand WHAT A BAD STUDENT YOU ARE!!
Input
There is a number (T)in the first line , tell you the number of test cases below. For the next T lines, there is just one number on the each line which tell you the N of the case.To simplified the problem , The N will be within 231 and more then 0.
Output
For each test case, print the N-th non square number and the result of the formula.
Sample Input
4
1
3
6
10
Sample Output
2 2
5 7
8 13
13 28


【题目分析】

这个题是找数学规律,分为两部分:
1.求第n个非平方数是多少?
此处证明略,稍后补充。
2.求题目中表达式 Mi=1i 的值。
对1~n的值求 i 可得:

n 1 2 3 4 5 6 7 8 9 10
An 1 1 1 2 2 2 2 2 3 3

i 个数满足 K2<=i<(K+1)2 K 为第 n 个数之前的那个平方数
K+12K2=2K+1 ;
对于每一个 K 都有 (2K+1)K ;
N 前面的那个平方数为 M=n
则有 M1=A 个这样的 K
这些项的和为: A(A+1)(2A+1)3+A+1A2
N2 的前n项和的公式为 n(n+1)(2n+1)6 ,高中数学)
再加从 M2 ~ N 的数之和 NMM+1×M ;
所以总和为 A(A+1)(2A+1)3+A+1A2+NMM+1×M

【代码】

#include<stdio.h>
#include<math.h>
int main() {
    int t;
    scanf("%d", &t);
    while (t--) {
        long long int n, m, a;
        scanf("%lld", &n);
        long long int sum = 0;
        n = n + sqrt(n * 1.0) + 0.5;
        m = sqrt(n * 1.0);
        a = m - 1;
        sum = (a * (a + 1) * (2 * a + 1)) / 3 + (a * (a + 1)) / 2 + (n - m * m + 1) * m;
        printf("%lld %lld\n", n, sum);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_26122455/article/details/78808783