我试图解决这个问题: https://www.hackerrank.com/contests/projecteuler/challenges/euler003/submissions/code/2977447
13195的主要因素是5,7,13和29。
给定数字N的最大素数因子是什么?
输入格式 第一行包含T,测试用例的数量。接下来是T行,每行包含一个整数N.
输出格式 对于每个测试用例,显示N的最大素数因子。
约束
1≤T≤10 10≤N≤1012
我的代码在第五次测试时遇到超时错误(我们不了解实际内容)。有没有想过为什么它没有通过测试?感谢
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
/* Author: Derek Zhu
* 1and1get2@gmail.com
* https://www.hackerrank.com/contests/projecteuler/challenges/euler003
* */
// The part of the program involving reading from STDIN and writing to STDOUT has been provided by us.
public class Solution {
public static boolean D = true;
static BufferedReader in = new BufferedReader(new InputStreamReader(
System.in));
static StringBuilder out = new StringBuilder();
public static void main(String[] args) throws NumberFormatException,
IOException {
int numOfCases = Integer.parseInt(in.readLine());
for (int i = 0; i < numOfCases; i++){
calculateCase(Long.parseLong(in.readLine()));
}
}
private static void calculateCase(Long input) throws IOException{
if (D) System.out.println("Processing: " + input);
long largestPF = prime(input);
if (D) System.out.print("Final calculate: ");
System.out.println(largestPF);
}
private static long prime(long n){
long i = 2;
while ( n % i != 0 && i < n){
i ++;
}
if (D) System.out.println("found i: " + i);
if (i < n){
return prime(n/i);
} else {
return n;
}
}
public static int primeFactors(BigInteger number) {
BigInteger copyOfInput = number;
int lastFactor = 0;
for (int i = 2;
BigInteger.valueOf(i)
.compareTo(copyOfInput) <= 0; i++) {
if (copyOfInput.mod(BigInteger.valueOf(i))
.compareTo(BigInteger.ZERO) == 0)
{
lastFactor = i;
copyOfInput = copyOfInput
.divide(BigInteger.valueOf(i));
i--;
}
}
return lastFactor;
}
}
答案 0 :(得分:0)
谢谢@ajb
事实证明,采用另一种方法会非常有效。
private static long method2(long NUMBER){
long result = 0;
for(int i = 2; i < NUMBER; i++) {
if(NUMBER % i == 0 && isPrime(NUMBER / i)) {
result = NUMBER / i;
break;
}
}
return result;
}
private static boolean isPrime(long l) {
for(long num = 2, max = l / 2 ; num < max; num++) {
if(l % num == 0) {
return false;
}
}
return true;
}
完整的代码与时间的比较可以在这里找到: https://github.com/1and1get2/hackerrank/blob/master/Contests/ProjectEuler%2B/003_LargestPrimeFactor/src/Solution.java