题目如下:
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
Inputcopy | Outputcopy |
---|---|
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类型的,然后再强转,这样也会因为小数部分也相加减而产生误差。