Find Largest Prime Factor of a Number Using C++



Consider we have an element x, we have to find the largest prime factor of x. If the value of x is 6,  then-largest prime factor is 3. To solve this problem, we will just factorize the number by dividing it with the divisor of a number and keep track of the maximum prime factor.

Example

 Live Demo

#include <iostream>
#include<cmath>
using namespace std;
long long getMaxPrimefactor(long long n) {
   long long maxPF = -1;
   while (n % 2 == 0) {
      maxPF = 2;
      n /= 2;
   }
   for (int i = 3; i <= sqrt(n); i += 2) {
      while (n % i == 0) {
         maxPF = i;
         n = n / i;
      }
   }
   if (n > 2)
   maxPF = n;
   return maxPF;
}
int main() {
   long long n = 162378;
   cout << "Max Prime factor of " << n << " is " << getMaxPrimefactor(n);
}

Output

Max Prime factor of 162378 is 97
Updated on: 2019-10-30T05:53:55+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements