【HDU 5879】Cure(暴力&优化 详解)

 Given an integer nnn, we only want to know the sum of 1/k21/k^21/k2 where kkk from 111 to nnn. 

Input
There are multiple cases.
For each test case, there is a single line, containing a single positive integer nnn.
The input file is at most 1M.
Output
The required sum, rounded to the fifth digits after the decimal point.
Sample Input

1
2
4
8
15

Sample Output

1.00000
1.25000
1.42361
1.52742
1.58044

题意描述:对于给的数n,求n前每个数平方倒数总和

解题思路:用for循环计算就行

易错分析:注意本题没有给n的范围,如果我们用int型或long型的话,当1后面有好多0的时候结果就1.#INF0或者是0.00000,所以我们必须要以字符串形式输入。因为我们精度只需要小数点后5位,所以当n值特别大的时候,有的值会相同,找出来大概是120000,所以就不用计算它后面的数值直接等于120000即可,这样就可以在字符串长度大于6时,直接输出极限值;长度小于6时,给它转化成数字去计算就行了

其他:因为for循环计算平方时120000数据会溢出,所以不能用int存,然后就是120000前还有一部分是在某段内值相同,所以也可以分好两种情况来写(具体看代码)

AC

#include<stdio.h>
#include<string.h>
typedef long long ll;
char s[1200000];//注意数组开的范围 
int main(void)
{
	double sum;
	while(~scanf("%s",s))
	{
		sum=0.0;
		int len;
		len=strlen(s);
		if(len>6)
			printf("1.64493\n");
		else
		{
			int n; 
			sscanf(s,"%d",&n);//字符串转化 
			if(n >= 120000)
				printf("1.64493\n");
			else
			{
				/*因为和120000比较,所以此处i用long型或者double  int型乘的时候会溢出
				  想用int也可以,把i的数值缩小,即 
				  if(n >= 110292) printf("1.64493\n");
				  else if(n >= 52447) printf("1.64492\n"); 
				 */
				for(ll i=1;i<=n;i++)
				{
					sum+=(double)(1.0/(i*i*1.0))*1.0;
				}
				printf("%.5lf\n",sum);
			}
		}
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/m0_58245389/article/details/121035931