Find sum of a number and its maximum prime factor | C ++ program to find sum of n and it 's largest prime factor ; Function to return the sum of n and it 's largest prime factor ; Initialise maxPrime to - 1. ; n must be odd at this point , thus skip the even numbers and iterate only odd numbers ; This condition is to handle the case when n is a prime number greater than 2 ; finally return the sum . ; Driver Program to check the above function .
#include <cmath> NEW_LINE #include <iostream> NEW_LINE using namespace std ; int maxPrimeFactors ( 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 ; int sum = maxPrime + num ; return sum ; } int main ( ) { int n = 19 ; cout << maxPrimeFactors ( n ) ; return 0 ; }