有9个因数的数
Description
Find the count of numbers less than N having exactly 9 divisors
1<=T<=1000,1<=N<=10^12
Input
First Line of Input contains the number of testcases. Only Line of each testcase contains the number of members N in the rival gang.
Output
Print the desired output.
Sample Input 1
2
40
5
Sample Output 1
1
0
求[1,N]之间有九个因子的数
此题技巧有九个因子的数满足下面条件之一
n=a^2 * b^2
n=a^8
其中a和b为质数。
求[1,N]范围内的所有质数
1不是质数
/**
* 求num范围内的所有质数
* @param num
*/
public static void getPrime(long num) {
list = new ArrayList<Integer>();
int l = (int) Math.sqrt(num)+1; //l为num的平方根向上取整
a = new int[l];
for (int i = 2; i < a.length; i++) {
if (a[i] == 0) {
list.add(i);
for (int j = 2 * i; j < a.length; j = j + i) {
a[j] = 1;
}
}
}
}
求有9个因子的数
public static long getCount(long num) {
long res = 0;
for (int i = 0; i < list.size() - 1; i++) {
for (int j = i + 1; j < list.size(); j++) {
if (Math.pow(list.get(i) * list.get(j), 2) > num)
break;
res++;
}
}
for (int i = 0; i < 9 && i < list.size(); i++) { //注意,这里i<9是为了防止用例问题而添加的
if (Math.pow(list.get(i), 8) > num) {
break;
}
res++;
}
return res;
}
完整代码
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* 找到一个数,它含有9个因数,比如 36: 1 2 3 4 6 9 12 18 36
*
* 实际上是一个数学公式题,有9个因数的数必定满足下列公式之一
*
* x = a2 * b2
* x = a8
* 其中a,b是质数,因此只要枚举质数即可
*/
public class Main {
static int[] a;
static List<Integer> list;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int nu = sc.nextInt();
int[] a = new int[10000];
for (int p = 0; p < nu; p++) {
long num = sc.nextLong();
getPrime(num);
System.out.println(getCount(num));
}
}
/**
* 求num范围内的所有质数
* @param num
*/
public static void getPrime(long num) {
list = new ArrayList<Integer>();
int l = (int) Math.sqrt(num)+1; //l为num的平方根向上取整
a = new int[l];
for (int i = 2; i < a.length; i++) {
if (a[i] == 0) {
list.add(i);
for (int j = 2 * i; j < a.length; j = j + i) {
a[j] = 1;
}
}
}
}
public static long getCount(long num) {
long res = 0;
for (int i = 0; i < list.size() - 1; i++) {
for (int j = i + 1; j < list.size(); j++) {
if (Math.pow(list.get(i) * list.get(j), 2) > num)
break;
res++;
}
}
for (int i = 0; i < 9 && i < list.size(); i++) { //注意,这里i<9是为了防止用例问题而添加的
if (Math.pow(list.get(i), 8) > num) {
break;
}
res++;
}
return res;
}
}