hdu 1597 find the nth digit(数学题)

来源:互联网 发布:大唐电信数据所招聘 编辑:程序博客网 时间:2024/06/05 18:21

原题链接:

http://acm.hdu.edu.cn/showproblem.php?pid=1597



方法1:直接循环找到所在那两个数之间。

方法2:求根公式。

x^2+x-2*n>=0(x为Sx的下标,n为第n个数)

求根公式得(sqrt(8*n+1)-1)/2   ,另一情况为负数舍去。

关键:求出这个double类型,应该满足>=0,所以向上取整。


注意:1<=n<(2^31),所以用unsigned int或者long long



代码如下:

方法1:

#include<iostream>using namespace std;int main(){int T;cin >> T;while (T--){int n;cin >> n;int sum = 0;int k = 1;while (sum < n){sum += k;k++;}int temp=sum - k+1;int ans = (n - temp) % 9 ? (n - temp) % 9 : 9;cout << ans << endl;}return 0;}

方法2:

#include<iostream>#include<cmath>#include<cstdio>using namespace std;int main(){int T;scanf("%d", &T);while (T--){long long int n;scanf("%d", &n);long long int k=ceil((sqrt(8.0 * n + 1) - 1) / 2.0);long long int temp = k* (k - 1) / 2;int ans = (n - temp) % 9 ? (n - temp) % 9 : 9;cout << ans << endl;}return 0;}


0 0
原创粉丝点击