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 sum of a number and its maximum prime factor in C++
Suppose we have a positive number n, and we have to find the sum of N and its maximum prime factor. So when the number is 26, then maximum prime factor is 13, so sum will be 26 + 13 = 39.
Approach is straight forward. Simply find the max prime factor, and calculate the sum and return.
Example
#include<iostream>
#include<cmath>
using namespace std;
int maxPrimeFact(int n){
int num = n;
int maxPrime = -1;
while (n % 2 == 0) {
maxPrime = 2;
n /= 2;
}
for (int i = 3; i <= sqrt(n); i += 2) {
while (n % i == 0) {
maxPrime = i;
n = n / i;
}
}
if (n > 2)
maxPrime = n;
return maxPrime;
}
int getRes(int n) {
int sum = maxPrimeFact(n) + n;
return sum;
}
int main() {
int n = 26;
cout << "Sum of " << n <<" and its max prime factor is: " << getRes(n);
}
Output
Sum of 26 and its max prime factor is: 39
Advertisements