Find sum of a number and its maximum prime factor in C++

C++Server Side ProgrammingProgramming

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

 Live Demo

#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
raja
Published on 19-Dec-2019 12:15:36
Advertisements