We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
public static int largestPrimeDivisor(long n) {
int largestPrime = -1;
while (n % 2 == 0) {
largestPrime = 2;
n /= 2;
}
for (int i = 3; i * i <= n; i += 2) {
while (n % i == 0) {
largestPrime = i;
n /= i; // Remove the factor i from n
}
}
if (n > 1) {
largestPrime = (int) n;
}
return largestPrime;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for (int testCaseIndex = 0; testCaseIndex < t; testCaseIndex++) {
long n = in.nextLong();
int result = largestPrimeDivisor(n);
System.out.println(result);
}
in.close();
}
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Join us
Create a HackerRank account
Be part of a 26 million-strong community of developers
Please signup or login in order to view this challenge
Project Euler #3: Largest prime factor
You are viewing a single comment's thread. Return to all comments →
can anyone make my code more optimized
import java.io.; import java.util.;
public class Solution {
}