Prime Factorization Program in Java

后端 未结 12 1602
自闭症患者
自闭症患者 2021-01-03 11:11

I am working on a prime factorization program implemented in Java. The goal is to find the largest prime factor of 600851475143 (Project Euler problem 3). I think I have m

12条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-03 12:05

        private static boolean isPrime(int k) throws IllegalArgumentException
         {
            int j;
    
            if (k < 2) throw new IllegalArgumentException("All prime numbers are greater than 1.");
            else {
                for (j = 2; j < k; j++) {
                    if (k % j == 0) return false;
                }
            }
    
            return true;
        }
    
        public static void primeFactorsOf(int n) {
            boolean found = false;
    
            if (isPrime(n) == true) System.out.print(n + " ");
            else {
                int i = 2;
                while (found == false) {
                    if ((n % i == 0) && (isPrime(i))) {
                        System.out.print(i + ", ");
                        found = true;
                    } else i++;
                }
                primeFactorsOf(n / i);
            }
        }
    

提交回复
热议问题