codeforces 622A A. Infinite Sequence (二分)
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.
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.
Print the element in the n-th position of the sequence (the elements are numerated from one).
3
2
5
2
10
4
55
10
56
1
题意:这么个数列,问第n个数是多少;
思路:结合n*(n+1)/2这个式子二分;
AC代码:
#include <bits/stdc++.h>
using namespace std;
long long bisearch(long long x)
{
long long le=0,ri=1e8,mid;
while(le<=ri)
{
mid=(le+ri)/2;
if(mid*(mid+1)/2>=x)ri=mid-1;
else le=mid+1;
}
return le-1;
}
int main()
{
long long n;
cin>>n;
long long ans=bisearch(n);
cout<<n-ans*(ans+1)/2<<"\n";
return 0;
}