java—优化这个最大的素因子程序的最佳方法

nhhxz33t  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(401)

我需要一些帮助来优化这个程序。我正试图找出输入的最大主因子。但是,它偶尔会有超时问题,所以我有兴趣找出如何优化它。

  1. import java.io.*;
  2. import java.util.*;
  3. import java.text.*;
  4. import java.math.*;
  5. import java.util.regex.*;
  6. public class PFactor() {
  7. public static void main(String[] args) {
  8. Scanner in = new Scanner(System.in);
  9. int t = in.nextInt();
  10. for(int a0 = 0; a0 < t; a0++){
  11. long n = in.nextLong();
  12. System.out.println(pMod(n));
  13. }
  14. }
  15. public static int pMod(long d) {
  16. long maxVal = 0;
  17. for (long i = 2; i <= d; i++) {
  18. if (d % i == 0) {
  19. boolean prime = pCount(i);
  20. if (prime == true) {
  21. max = i;
  22. }
  23. } else {
  24. max = max;
  25. }
  26. }
  27. return (int)max;
  28. }
  29. public static boolean pCount(long inLong) {
  30. int count = 0;
  31. for (long s = 1; s <= inLong; s++) {
  32. if (inLong % s == 0) {
  33. count++;
  34. }
  35. }
  36. if (count == 2) {
  37. return true;
  38. } else {
  39. return false;
  40. }
  41. }
  42. }

你知道如何优化这段代码,使它没有那么多的超时?我需要这个很快准备好的东西在工作中,所以我决定伸手看看,如果我可以得到一些帮助,因为我似乎无法找出它需要进一步优化自己。

2j4z5cfb

2j4z5cfb1#

我真的找到了一个解决方案,伙计们,经过一点修补!不过你们都帮了大忙!谢谢你的帮助!

相关问题