现在的位置: 首页 > 综合 > 正文

Hackerrank Sherlock and Squares

2018年02月20日 ⁄ 综合 ⁄ 共 549字 ⁄ 字号 评论关闭

先上时间超了的代码

#include <iostream>
#include <cmath>
#include <algorithm>

using namespace std ;

int main()
{
	int t ;
	cin >>t ;
	while (t--)
	{
		int count = 0 ; 
	  long long	int a , b ;
		cin >> a  >> b ;
		
		for ( int i = a ; i <= b ; ++i)
		{
		         double result = sqrt(i) ;
		         if(i == result * result )++count ;
		}
		
		cout << count << endl ;
		
	}
	return 0 ;
}

这里面 时间超过 或者有 错误答案产生 主要是 在 result  * result 中产生 ,看网站上的 注释 说 如果 i * i  大于b 就会中断。 

正确的代码 ,未超时的代码。。。

#include <iostream>
#include <cmath>
#include <algorithm>

using namespace std ;

int main()
{
	int t ;
	cin >>t ;
	while (t--)
	{
		int count = 0 ; 
	  long long	int a , b ;
		cin >> a  >> b ;
		
		for ( int i = 1 ;  ; ++i)
		{
		         if(i*i > b) break ;
				 if(i * i >= a && i * i <= b)  ++count ;
		}
		
		cout << count << endl ;
		
	}
	return 0 ;
}

抱歉!评论已关闭.