Find the largest prime factor of the given number.
Example 1:
Input : n=10 Output: 5 //10=2*5 largest is 5
Approach:
Java
public class LargestPrimeFactor {
public static void main(String[] args) {
int n = 10;
int larger = largestPrime(n);
System.out.println(larger);
}
// method to find the largest prime
// factor of the given number
private static int largestPrime(int n) {
int larger = 2;
while (n % 2 == 0) {
n = n / 2;
larger = 2;
}
for (int i = 3; i * i <= n; i++) {
while (n % i == 0) {
larger = i;
n = n / i;
}
}
if (n > 1)
larger = n;
return larger;
}
}
C++
#include <bits/stdc++.h>
using namespace std;
//function to find the largest prime
//factor of the given number
int largestPrime(int n)
{
int larger=2;
while(n%2==0)
{
n=n/2;
larger=2;
}
for( int i=3;i*i<=n;i++)
{
while(n%i==0)
{
larger=i;
n=n/i;
}
}
if(n>1)
larger=n;
return larger;
}
int main()
{
int n=10;
int larger=largestPrime(n);
cout<<larger<<"\n";
return 0;
}
No comments:
Post a Comment