B - Squares and Cubes(补题)

题目如下:

Polycarp likes squares and cubes of positive integers. Here is the beginning of the sequence of numbers he likes: 1, 4, 8, 9, ....

For a given number nn, count the number of integers from 1 to n that Polycarp likes. In other words, find the number of such x that x is a square of a positive integer number or a cube of a positive integer number (or both a square and a cube simultaneously).

Input

The first line contains an integer t (1 ≤ t ≤ 20) — the number of test cases.

Then t lines contain the test cases, one per line. Each of the lines contains one integer n (1≤n≤10^9).

Output

For each test case, print the answer you are looking for — the number of integers from 1 to n that Polycarp likes.

Sample 1

InputcopyOutputcopy
6
10
1
25
1000000000
999999999
500000000
4
1
6
32591
32590
23125

        这道题让我们求的是你所输入的整数n之前所有的,像1, 4, 8, 9,…这样的“平方”和“立方”一共有多少个。但是时间只给了1s,而n的范围在1~1e9,这样看来,我们的计算量就会很大,很有可能会超时,也很麻烦,所以我们就可以通过计算它们的“平方根”和“立方根”,去减少我们的计算量。

        而在经过一系列的尝试后,我们可以发现这样一个公式:

        假设,结果为a,则(根号不好打,这里用幂的形式来代替)

        a = n^(1/2) + n^(1/3) - (n^(1/2))^(1/3)

代码实现:

#include<iostream>
#include<cmath>
using namespace std;
int main() {
	double t, n;
	cin >> t;
	for (int i = 0; i < t; i++) {
		cin >> n;
		int a = int(sqrt(n)) + int(cbrt(n)) - int(cbrt(sqrt(n)));
		cout << a << endl;
	}
	return 0;
}

这里需要注意几点:(以我写的代码为例)

       1.不能用pow来实现“根号2”和“根号3”,存在精度问题。

       2.不能因为“sqrt()”和“cbrt()”需要的都是double类型,就直接让a也是double类型的,然后再强转,这样也会因为小数部分也相加减而产生误差。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值