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.
class Solution {
static void Main(String[] args) {
int T = Convert.ToInt32(Console.ReadLine());
for (int a0 = 0; a0 < T; a0++) {
long n = Convert.ToInt64(Console.ReadLine());
long largestPrimeFactor = LargestPrimeFactor(n);
Console.WriteLine(largestPrimeFactor);
}
}
static long LargestPrimeFactor(long n) {
long largestPrime = 2;
// Divide the number by 2 until it's not divisible by 2.
while (n % 2 == 0) {
n /= 2;
}
// Check for other prime factors starting from 3.
for (long i = 3; i <= Math.Sqrt(n); i += 2) {
while (n % i == 0) {
largestPrime = i;
n /= i;
}
}
// If the remaining number is a prime greater than 2.
if (n > 2) {
largestPrime = n;
}
return largestPrime;
}
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Project Euler #3: Largest prime factor
You are viewing a single comment's thread. Return to all comments →
In C#:
using System;
class Solution { static void Main(String[] args) { int T = Convert.ToInt32(Console.ReadLine()); for (int a0 = 0; a0 < T; a0++) { long n = Convert.ToInt64(Console.ReadLine()); long largestPrimeFactor = LargestPrimeFactor(n); Console.WriteLine(largestPrimeFactor); } }
}