Project Euler Problem 3 Solution

Share Button

lego white background

Project Euler Problem 3 Solution:

The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ?

The following source code for Project Euler Problem 3 is the optimized solution of it. If you pass 13195 in
LargestPrimeFact method you will get its largest prime factor which is 29.

public class LargestPrimeFactor {
	static boolean isPrime(long n){
		for(long i=2;i<=n/2;i++){
			if(n%i==0){
				return false;												
			}
		}
		return true;	
	}

	static long LargestPrimeFact(long n){
		long largestPrime=0;
		for(long i=2;i<Math.sqrt(n)/2;i++){
			if(n%i==0){
				if(isPrime(i)){
					largestPrime=i;
				}
				}										
			}
		return largestPrime;
	}
	public static void main(String args[]) {
		System.out.println (LargestPrimeFact(600851475143L));
	}
}

OUTPUT:
6857

Comment below what you think about the solution I provide and give your suggestion if any. Please do not copy right our solution

 

Share Button