Project Euler #3: Largest prime factor

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

Answer : 6857

Hacker Rank Question

Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        for(int a0 = 0; a0 < t; a0++){
            long n = in.nextLong();
            long res = primeFactors(n);
            System.out.println(res);
        }
    }

    public static long primeFactors(long n){
        while (n%2==0){
            n /= 2;
        }
        int res=0;
        for (int i = 3; i <= Math.sqrt(n); i+= 2){
            while (n%i == 0){
                n /= i;
                res = i;
            }
        }
        if (n > 2){
            return n;
        }else{
            return res;
        }

    }
}

Comments

Popular Posts