java - 优化这个最大素因子程序的最佳方法
问题描述
我需要一些帮助来优化这个程序。我试图找出输入的最大主要因素。但是,它偶尔会出现超时问题,所以我有兴趣弄清楚如何优化它。
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class PFactor() {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int a0 = 0; a0 < t; a0++){
long n = in.nextLong();
System.out.println(pMod(n));
}
}
public static int pMod(long d) {
long maxVal = 0;
for (long i = 2; i <= d; i++) {
if (d % i == 0) {
boolean prime = pCount(i);
if (prime == true) {
max = i;
}
} else {
max = max;
}
}
return (int)max;
}
public static boolean pCount(long inLong) {
int count = 0;
for (long s = 1; s <= inLong; s++) {
if (inLong % s == 0) {
count++;
}
}
if (count == 2) {
return true;
} else {
return false;
}
}
}
您知道如何优化此代码以使其没有那么多超时吗?我需要尽快为工作中的某些事情做好准备,所以我决定伸出手来看看我是否能得到一些帮助,因为我自己似乎无法弄清楚它需要进一步优化的地方。
解决方案
经过一番修改后,我实际上找到了解决方案!不过,你们都非常有帮助!感谢您的帮助!
推荐阅读
- javascript - Three.js - 如何更新 Raycaster 和 Intersection 的对象位置
- r - 如何在 R 中通过 yaml.load() 保留 YAML 注释 (#)
- unity3d - 在 Unity 中使用 AspNetCore.SignalR.Client
- javascript - 如何自动单击包含特定单词的元素?
- amazon-web-services - 使用 CiphertextBlob 作为字符串获取 InvalidCiphertextException
- kubernetes - GKE:内部负载平衡的入口不起作用
- arrays - 如何在 SwiftUI 上创建一个空的“视图”数组?
- python - Python在二维数组中保存和读取灰度图像?
- html - 正面大小的最大值不影响浏览器字体大小
- java - SOAP XSD 根元素问题