A Cubic number and A Cubic Number
Problem Description
A cubic number is the result of using a whole number in a multiplication three times. For example, 3×3×3=27 so 27 is a cubic number. The first few cubic numbers are 1,8,27,64 and 125. Given an prime number p. Check that if p is a difference of two cubic numbers.
Input
The first of input contains an integer T (1≤T≤100) which is the total number of test cases.
For each test case, a line contains a prime number p (2≤p≤1012).
Output
For each test case, output ‘YES’ if given p is a difference of two cubic numbers, or ‘NO’ if not.
Sample Input
10
2
3
5
7
11
13
17
19
23
29
Sample Output
NO
NO
NO
YES
NO
NO
NO
YES
NO
NO
Source
输入输出测试
代码块
在做AC时,看到这个题目,我首先关注的是p的取值范围10的12次方,觉得这个算法不好写,肯定会超时,而且我并没有想到素数本身的特点,而是想着怎么用找规律的方法来实现这个算法,既不会超时又轻而易举的输出YES或NO,然而到最后我也没有提交成功,看到别人的代码后我就意识到了我的问题。
题目大意:给出一个素数,判断这个素数是否是两个立方数之差,
我们可以利用立方数的性质,p=x^3-y^3=(x-y)(x^2+xy+y^2),这个数既是立方数又是素数,素数的特点是除了1和本身外没有其他的因子,那么在(x-y)*(x^2+xy+y^2)这个式子中,只有(x-y)这一项可能为1,所以就x-y=1,x=y+1;
然后就用二分查找来做这个题目
把p的取值范围相当于值域,根据值域寻找定义域的取值范围,范围大概在0-1000000之内,就用二分查找在这个范围内查找素数。
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#define ll long long
using namespace std;
const int maxn=1e6+10;
ll t,n;
int main(){
scanf("%lld",&t);
while(t--){
scanf("%lld",&n);
ll i=1;
int flag=0;
ll aaaa;
while(i <= maxn){
aaaa=3*i*i+3*i+1;
if(aaaa == n){
flag=1;
break ;
}
i++;
if(aaaa > n)
break ;
}
if(flag)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
ll p;
scanf("%lld",&p);
ll l=0,r=1000000;
while(l<r)
{
ll m=(l+r)/2;
if((m+1)*(m+1)*(m+1)-m*m*m<p)l=m+1;
else r=m;
}
printf("%s\n",((l+1)*(l+1)*(l+1)-l*l*l==p ? "YES" : "NO"));
}
return 0;
}
#include<stdio.h>
#include<iostream>
using namespace std;
int main()
{
int t,i,j;
long long q,w,l,r;
cin>>t;
while(t--)
{
scanf("%d",&q);
l=0;
r=1000000;
while(l<r)
{
w=(l+r)/2;
if((w+1)*(w+1)*(w+1)-w*w*w<q)
l=w+1;
else
r=w;
}
printf("%s\n",(r+1)*(r+1)*(r+1)-r*r*r==q?"YES":"NO");
}
return 0;
}