CodeForces-622A.Infinite Sequence

来源:互联网 发布:银行程序员怎么样 编辑:程序博客网 时间:2024/04/27 03:47

Consider the infinite sequence of integers: 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5…. The sequence is built in the following way: at first the number 1 is written out, then the numbers from 1 to 2, then the numbers from 1 to 3, then the numbers from 1 to 4 and so on. Note that the sequence contains numbers, not digits. For example number 10 first appears in the sequence in position 55 (the elements are numerated from one).

Find the number on the n-th position of the sequence.

Input
The only line contains integer n (1 ≤ n ≤ 1014) — the position of the number to find.

Note that the given number is too large, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type.

Output
Print the element in the n-th position of the sequence (the elements are numerated from one).

Examples
input
3
output
2
input
5
output
2
input
10
output
4
input
55
output
10
input
56
output
1
思路:等差数列求和。
1)暴力

#include<iostream>using namespace std;int main(){    long long n, i, x=0;    scanf("%lld", &n);    for (i = 0;x+i<n; i++)        x = (1 + i)*i / 2;    //x为前i项和,即数目之和    printf("%lld\n", n - x);    return 0;}
#include<iostream>using namespace std;int main(){    long long n, i;    scanf_s("%lld", &n);    for (i = 1; i < n; i++)        n -= i;    printf("%lld\n", n);    return 0;}

2)二分

#include<iostream>using namespace std;long long Solve(long long N){    int l = 0, r = 15000000;    long long mid, x;    while (l <= r)    {        mid = (l + r) / 2;        x = (1 + mid)*mid / 2;        if (x< N && x + mid + 1 >= N)            return x;        else if (x + mid + 1 < N)            l = mid + 1;        else if (x >= N)            r = mid - 1;    }}int main(){    long long n, x;    scanf("%lld", &n);    x = Solve(n);    printf("%lld\n",n - x);    return 0;}
0 0
原创粉丝点击