Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

โปรแกรม Java หาผลรวมตัวหารน้อยที่สุด (Minimum Sum of Factors)

โจทย์: Minimum Sum of Factors

แยก n เป็นผลคูณของตัวเลข > 1 ให้ผลรวมของตัวเลขเหล่านั้นน้อยที่สุด
คำตอบ: ผลรวมของ Prime Factors (รวมซ้ำ)

เหตุผล

สำหรับ composite factor a × b = c (a,b > 1): a + b ≤ c (ยกเว้น 2×2=4)
→ แยกเป็น prime factors ให้ผลรวมน้อยที่สุด

ตัวอย่างโค้ด


public class Demo {
    static int minSumFactors(int n) {
        int sum = 0;
        
        // Factor 2
        while (n % 2 == 0) {
            sum += 2;
            n /= 2;
        }
        
        // Odd factors
        for (int p = 3; p * p <= n; p += 2) {
            while (n % p == 0) {
                sum += p;
                n /= p;
            }
        }
        
        // Remaining prime
        if (n > 1) {
            sum += n;
        }
        
        return sum;
    }
    
    public static void main(String[] args) {
        int n = 350; // 350 = 2 × 5² × 7
        // Sum = 2 + 5 + 5 + 7 = 19
        System.out.println("Minimum sum of factors of " + n + " = " + minSumFactors(n));
    }
}

ผลลัพธ์

Minimum sum of factors of 350 = 19

ตัวอย่างอื่นๆ

Complexity

  • Time: O(√n)
  • Space: O(1)
nPrime FactorizationMin Sum
122² × 32+2+3=7
362² × 3²2+2+3+3=10
1002² × 5²2+2+5+5=14
13 (prime)1313