Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
Advertisements