A - Infinite Sequence
Problem description
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 1to 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 longinteger type.
Output
Print the element in the n-th position of the sequence (the elements are numerated from one).
Examples
Input3Output
2Input
5Output
2Input
10Output
4Input
55Output
10Input
56Output
1
解題思路:簡單推導:假設k表示為第k個序列(1,...,k),則前k個序列一共有n=(k+1)*k/2個數,所以求第n個數所在序列為第floor(√(2*n+0.25)-0.5)(下取整)個。因為n必須剛好為前k個序列數字的總個數時,k才會是精確的第k個序列,這時只需判斷m=(k+1)*k/2是否大於n,如果n大於m,說明第n個數實際在第k+1個序列裏面,則這個數為n-m;否則第n個數就在第k個序列裏面,則這個數為k-(m-n)=k+n-m。
AC代碼:
1 #include<bits/stdc++.h> 2 using namespace std; 3 int main(){ 4 long long n,k,m; 5 cin>>n; 6 k=sqrt(2.0*n+0.25)-0.5; 7 m=k*(k+1)/2; 8 if(n>m)cout<<n-m<<endl; 9 else cout<<k+n-m<<endl; 10 return 0; 11 }
A - Infinite Sequence