Find the largest prime number factor?

前端 未结 7 1759
别那么骄傲
别那么骄傲 2021-01-29 08:40

I need to find The prime factors of 13195 are 5, 7, 13 and 29. / * Largest is 377. * / What is the largest prime factor of the number 600851475143 ?

#include<         


        
7条回答
  •  北恋
    北恋 (楼主)
    2021-01-29 09:23

    public class LargeFactor{
    
         public static void main(String []args){
         long num = 600851475143L;
         long largestFact = 0;
         long[] factors = new long[2];
    
        for (long i = 2; i * i < num; i++) {
             if (num % i == 0) { // It is a divisor
            factors[0] = i;
            factors[1] = num / i;
    
            for (int k = 0; k < 2; k++) {
                boolean isPrime = true;
                for (long j = 2; j * j <  factors[k]; j++) {
                    if (factors[k] % j == 0) {
                        isPrime = false;
                        break;
                     }
                 }
                 if (isPrime && factors[k] > largestFact) {
                    largestFact = factors[k];
                 }
                }
            }
         }
         System.out.println(largestFact);
    }
    }
    

    Above code utilises the fact that we only need to check all numbers up to the square root when looking for factors.

提交回复
热议问题