首页 > 解决方案 > 优化这个最大素因子程序的最佳方法

问题描述

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

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;
        }
    }
}

您知道如何优化此代码以使其没有那么多超时吗?我需要尽快为工作中的某些事情做好准备,所以我决定伸出手来看看我是否能得到一些帮助,因为我自己似乎无法弄清楚它需要进一步优化的地方。

标签: javaoptimizationtimeoutprime-factoring

解决方案


经过一番修改后,我实际上找到了解决方案!不过,你们都非常有帮助!感谢您的帮助!


推荐阅读