标签:
1. 问题:
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
2. 解法(by java in Eclipse)
1 package com.lun.alrithmetic; 2 /* 3 * Q1: what‘s the primary factor? (1 2 3) 4 * Q2: i & i+2ne能否遍历出所有质数 5 */ 6 7 public class LargestPrimeFactor { 8 9 public static void main(String[] args) { 10 // TODO Auto-generated method stub 11 long n = 600851475143L; 12 System.out.println("The largest prime factor of the number ‘600851475143‘ is "+largestPrimeFactor(n)); 13 } 14 15 public static boolean isPrime(long n){ 16 if(n<4) 17 return n>1; 18 if(n%2==0 || n%3==0) 19 return false; 20 for(long i=5; i*i<n; i+=6) 21 if(n%i==0 || n%(i+2)==0) 22 return false; 23 return true; 24 } 25 26 public static long largestPrimeFactor(long n){ 27 if(n%2==0){ 28 while(n%2==0) 29 n /= 2; 30 } 31 if(n%3==0){ 32 while(n%3==0) 33 n /= 3; 34 } 35 for(int i=5; i*i<n; i+=6){ 36 if(n%i==0){ 37 while(n%i==0) 38 n /= i; 39 } 40 int j = i+2; 41 if(n%j==0){ 42 while(n%j==0) 43 n /= j; 44 } 45 } 46 return n; 47 } 48 }
1 package com.lun.alrithmetic; 2 /* 3 * Question: What‘s the largest prime factor of the number ‘600851475143‘ ? 4 * Function: Divide & Conquer, analyse prime factor 5 */ 6 7 public class LargestPrimeFactor2 { 8 9 public static void main(String[] args) { 10 // TODO Auto-generated method stub 11 long n = 600851475143L; 12 System.out.println("The largest prime factor of the number ‘600851475143‘ is "+largest(n)); 13 } 14 15 public static boolean isPrime(long n){ 16 if(n<4) 17 return n>1; 18 if(n%2==0 || n%3==0) 19 return false; 20 for(long i=5; i*i<n; i+=6) 21 if(n%i==0 || n%(i+2)==0) 22 return false; 23 return true; 24 } 25 26 public static long largest(long n){ 27 if(isPrime(n)) 28 return n; 29 else{ 30 if(n%2==0) 31 return largest(n/2); 32 if(n%3==0) 33 return largest(n/3); 34 for(long i=5; i*i<n; i+=6){ 35 if(n%i==0) 36 return largest(n/i); 37 if(n%(i+2)==0) 38 return largest(n/(i+2)); 39 } 40 } 41 42 return 1; 43 } 44 45 }
注:利用分解质因数的方法,从小向大用质数整除(如果此质数恰好是n的因数的话)n,即不断的减小n的规模,最后即可求的最大质因数。
法二,采用了递归的方法易于理解,但是内存消耗较大;建议用法一。
The largest prime factor(最大质因数)
标签:
原文地址:http://www.cnblogs.com/lunlv/p/4944826.html