finding out the divisors of a number - c++

What is the most optimized approach of finding out the number of divisors of a number,such that the divisors have at least the digit 3 in it?
e.g. 21=1,3,7,21
therefore only one divisor has the digit 3 in it.
e.g.
62=1,2,31,62
therefore only one divisor has the digit 3 in it and i.e. 31
EDIT-i realized that the best way to do this woulds be to find out all the factors of a number and check for the factors containing the digit 3.
the best way to find out the factors :
Getting Factors of a Number
What is the best way to get all the divisors of a number?

Here is an expansion on my take. It first checks if there is a possible factor in the list div3. If not, it adds candidates up to number/2, skipping values that already could be factored according to this list, so '37' and '43' get added, but not '36' or '39'.
The above part should be considered "setup". If you know the input constraints (a maximum input value), you can calculate the vector div3 once, then store it inside the program.
If the list div3 is up to date, the input should be factored into one of these numbers. If it can't then none of its factors contain a '3'. If it can, this shows the remainder, which can be factored further using conventional methods.
I consider this "optimized" because the constraint "any factor should contain a '3'" is checked first. Only if any valid factor is found, you need to calculate all the others.
My first program using <vector> and its ilk, so be gentle in your comments :-)
(Edit) I now notice the factor checking loop goes over the entire div3 vector. Of course, it only needs to go up to number/2. Left as an exercise to the reader.
(Additional edit) find3 is here a reverse iterator. For some reason that seemed appropriate, but I can't recall why I thought so :) If checking up to and including number/2, you need to change it to a regular forward iterator.
#include <iostream>
#include <vector>
using namespace std;
int contains_3 (int value)
{
while (value && (value % 10) != 3)
value /= 10;
return value;
}
int main (int argc, char **argv)
{
int number, found_flag, last_div3, adjust, adjust_digit;
vector<int> div3;
vector<int>::reverse_iterator find3;
vector<int>::iterator it;
// a little seeding
div3.push_back(3);
div3.push_back(13);
div3.push_back(23);
if (argc != 2)
return -1;
number = atoi (argv[1]);
found_flag = 0;
// do we need to expand div3?
last_div3 = div3.back();
while (last_div3 * 2 < number)
{
// if this number contains a '3' in any other place than the last,
// simply increment it
if ((last_div3 % 10) != 9 && contains_3(last_div3/10))
{
last_div3++;
} else
{
// no? then simply pick the next multiple of 10 and add 3
last_div3 /= 10;
last_div3++;
last_div3 *= 10;
if (!contains_3(last_div3))
last_div3 += 3;
}
// check if it should be in the list
for (it = div3.begin() ; it != div3.end() && (last_div3 % *it); ++it) ;
if (it == div3.end())
{
div3.push_back(last_div3);
}
}
cout << "list is now: ";
for (it = div3.begin() ; it != div3.end(); ++it)
cout << ' ' << *it;
cout << endl;
for (find3 = div3.rbegin(); !found_flag && find3 != div3.rend(); find3++)
{
if (!(number % *find3))
{
cout << "candidate: " << *find3 << ", remaining to sieve: " << number/(*find3) << endl;
found_flag++;
}
}
if (!found_flag)
cout << "None found" << endl;
return 0;
}

Related

Is there a way to factorize large numbers in c++

I've written the following C++ code to factorize really large numbers efficiently (numbers up to 24997300729).
I have a vector containing 41000 primes approx.( I know having such a large vector isn't a good idea although but couldn't figure a way around this).
This code produces the prime factorization of moderately large numbers in no time but when it comes to numbers such as, 24997300572 the program stalls.
Here's the program below with some screenshots of the output:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <cmath>
using namespace std;
vector<int> primes = {paste from
https://drive.google.com/file/d/1nGvtMMQSa9YIDkMW2jgEbJk67P7p54ft/view?usp=sharing
};
void factorize(int n) {
if (n == 1)
return;
if (find(primes.begin(), primes.end(), n) != primes.end()) {
cout << n <<" "; //if n is prime dont'proceed further
return;
}
//obtaining an iterator to the location of prime equal to or just greater than sqrt(n)
auto s = sqrt(n);
vector<int>::iterator it = lower_bound(primes.begin(), primes.end(), s);
if (it == primes.end()) {
return; // if no primes found then the factors are beyond range
}
for (auto i = it;i != primes.begin();i--) {
if (n % *i == 0)
{
cout << *i << " ";
n = n / (*i);
factorize(n);
return; // the two consecutive for() loops should never run one after another
}
}
for (auto i = it;i != primes.end();i++) {
if (n % *i == 0)
{
cout << *i << " ";
n = n / (*i);
factorize(n);
return; // the two consecutive for() loops should never run one after another
}
}
}
int main() {
unsigned int n;
cout << "Enter a number between 1 and 24997300729 ";
cin >> n;
if (n > 24997300729) {
cout << "Number out of range;";
exit(-1);
}
factorize(n);
return 0;
}
This is OK
But This is NOT!!!
I tried using long long int and long double wherever I could to over come the problem of large numbers, but that didn't help much.
Any help Would Be Greatly Appreciated
It's a little unclear (at least to me) exactly why you've structured the program the way you have.
You can fully factor a number by only looking for prime factors less than or equal to that number's square root. Any prime factor larger than those pairs with one prime factors smaller than that, so you only have to search for those to find all the prime factors. Any remaining factors can be obtained by simple division, not searching.
I'd probably generate the base of prime numbers on the fly (mostly likely using a sieve). The square root of 24'997'300'729 is (about) 158'105. A quick test shows that even without any work on optimization, a sieve of Eratosthenes will find the primes up to that limit in about 12 milliseconds.
Personally, I'd rather not have a fixed limit on the largest number the user can factor, other than the limit on the size of number we're working with, so if the user enters something close to the limit for a 64-bit number, we find all the primes that fit in 32 bits, and then use those to factor the number. This will obviously be slower than if we don't find as many primes, but a user probably won't be too surprised at the idea that factoring a larger number takes longer than factoring a smaller number.
So, implementing that, we might end up with code something like this:
#include <iostream>
#include <locale>
#include <vector>
#include <string>
using Number = unsigned long long;
auto build_base(Number limit) {
std::vector<bool> sieve(limit / 2, true);
for (Number i = 3; i < limit; i += 2) {
if (sieve[i / 2]) {
for (Number temp = i * i; temp < limit; temp += i)
if (temp & 1)
sieve[temp / 2] = false;
}
}
return sieve;
}
void factor(Number input, std::vector<bool> const &candidates)
{
while (input % 2 == 0) {
std::cout << 2 << "\t";
input /= 2;
}
for (Number i = 1; i < candidates.size(); i++) {
if (candidates[i]) {
auto candidate = i * 2 + 1;
while ((input % candidate) == 0) {
std::cout << candidate << "\t";
input /= candidate;
}
}
}
if (input != 1)
std::cout << input;
}
int main(int argc, char **argv) {
std::cout.imbue(std::locale(""));
if (argc != 2) {
std::cerr << "Usage: factor <number>\n";
return EXIT_FAILURE;
}
auto number = std::stoull(argv[1]);
auto limit = std::sqrt(number) + 1;
auto candidates = build_base(limit);
factor(number, candidates);
}
At a high level, the code works like this: we start by finding the primes up to the square root of the number the user entered. Since we want all the primes up to a limit, we use a sieve of Eratosthenes to find them. This builds a vector of bools, in which vector[n] will be true if n is prime, and false if n is composite. It does this starting from 3 (2 is a special case we kind of ignore for now) and crossing off the multiples of three. Then it finds the next number that hasn't been crossed off (which will be five, in this case), and crosses off its multiples. It continues doing that until it reaches the end of the array. To save some space, it leaves all the even numbers out of the array, because (other than that special case for 2) we already know none of them is prime.
Once we have that, we use those prime numbers to find prime factors of the number we want to factor. This proceeds pretty simply: walk through the vector of primes, and test whether each prime number divides evenly into the target number. If it does, print it out, divide it out of the target number, and continue.
At least for me, this seems to work pretty dependably, and is reasonably fast. If we wanted to do a better job of factoring larger numbers, the next big step would be to switch to a segmented sieve. This can improve the speed of the first part of the job by a pretty wide margin, allowing us (for example) to factor anything that'll fit into a 64-bit number in no more than about 10 seconds.

My C++ prime number identifier and prime factor finder has a bug [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm a beginner to C++ and this website, so any dumb mistakes are out of ignorance. For practice, I'm trying to write a program that identifies a prime number and gives a composite's prime factors if the user requests. The prime IDer works, but the prime factors do not. When I type in twelve as my number, it gives me the factors 2 3 and 5, and 12's prime factors are 2 2 and 3. What am I messing up? Here is the code. Don't mind the weird spaces or names.
#include <iostream>
#include <vector>
#include <cmath>
#include <string>
//Printing factors help
void print(std::vector<int> const& factors)
{
for (int i = 0; i < factors.size(); i++) {
std::cout << factors.at(i) << ' ';
}
}
int main() {
//Restarting it
std::string again;
again = "Yes";
//Actual loop
while (again == "Yes") {
//Variable/vectors
std::string pfacts;
double input = 0;
double result = 0;
double looper = 2;
int looper2 = 2;
int printed = 0;
int printed2 = 0;
std::vector<int> factors;
std::vector<int> holders;
//Asking for number
std::cout << "Please enter your number.\n";
std::cin >> input;
double holder = input;
//Ratting out trolls
if (input == 0) {
std::cout << "Your number is neither.\n";
looper = 1000003;
}
if (input == 1) {
std::cout << "Your number is neither.\n";
looper = 1000003;
}
//Prime/composite loop
while (looper < 1000002 and input != 1 and fmod(result, 1) == 0) {
result = input / looper;
//Finding composite
if (fmod(result, 1) == 0 and printed == 0) {
std::cout << "Your number is composite.\n";
printed = 1;
looper = 1000003;
}
//Finding prime
else if (fmod(result, 1) != 0 and printed2 == 0) {
std::cout << "Your number is prime.\n";
printed2 = 1;
}
}
//Asking about factors
if (printed == 1) {
std::cout << "Would you like to know it's prime factors? (Please type Yes or No exactly)\n";
std::cin >> pfacts;
}
//Actually finding them
if (pfacts == "Yes") {
while (looper2 < 1000002) {
if (holder / looper2 == 0) {
factors.push_back(holder);
looper2 = 1000003;
}
if (looper2 < 1000002 and fmod (fmod(holder, looper2), 1) == 0 and looper2 % 2 != 0 or looper2 / 2 == 1) {
factors.push_back(looper2);
holder = holder / looper2;
}
looper2 = looper2 + 1;
}
//Printing them
print(factors);
std::cout << "\n";
}
//Again?
std::cout << "Do you need to input another number? (Please type, exactly: Yes or No)\n";
std::cin >> again;
}
}
You're just making a really simple thing more complex with that looper , printed stuff,
a good programmer is one which solves hard things in easy way.
So it is hard to understand for me to know exactly what you're doing in the code above at least not without enough comments.
So here is my solution, i am just providing the algorithm so you can write your own code and learn from it.
First note things below.
A prime number is a positive integer which has exactly two factors first is 1 and another is that number itself , so two is smallest prime number.
A number is also prime if it is not divisible from 2 to its square root, you should consider this fact for performance.
Now the algorithm:
Take the number in a variable num.
Check if it is positive integer greater then 1, if not then it is not a prime.
Take num's squareroot with help of sqrt() function in variable num as you don't need original num any more.
Now add one to num and take its absolute value.
Start a loop from i = 2 to num: you're starting from 2 because two is the smallest prime.
In every iteration check num % i == 0, if yes then it is not a prime and you break, otherwise don't do anything.
Now after the loop ends check if i == num, if yes that means you never broke the hence the number is prime and you're done, otherwise you broke the loop hence the number is not prime and you ask for prime factors.
Now again you start from j = 2 to num.
Now if num % j == 0, you print j and do num = num / j, otherwise you increment j.
I hope it is helpful. I didn't test it on an IDE, because I don't have one because I don't write c++ code anymore. Tell me if you find any bugs.

Why is using all numbers to test for a prime number faster than using prime numbers only

I made this program for generating prime numbers. I know there are lots of formulas for generating them 100x faster, but this is what I did.
I tried to divide i with all numbers under i. That was the simplest method, but I though it was inefficient, since after dividing by 2 you don't need to divide by 4 and so on.
I made a list of prime numbers smaller than i, and divided i by that list's numbers. I went through the list using std::iterator, because I saw it being used in all stackoverflow answers and other tutorials. It turned out to be a lot slower. Like it took 22 seconds instead of 2.
I tried to use an int to go through the list, and it took 2 seconds again.
Next, I used 1 000 000 to see the difference between method 1 and 3. To my amazement method 1 was faster. Why is that? Shouldn't using only prime numbers to test be faster than using all numbers?
#include <iostream>
#include <vector>
#include <chrono>
int main()
{
std::cout << "how high do you want to generate prime numbers? ";
int x;
// typed 1 000 000
std::cin >> x;
auto starttime = std::chrono::high_resolution_clock::now();
std::vector<unsigned int> primes;
bool isPrime;
for (int i = 2; i <= x; ++i) {
isPrime = true;
// takes 293 seconds
//for (int div{ 2 }; div < i; ++div) {
// if ((i % div) == 0) {
// takes really really long
//for (std::vector<unsigned int>::iterator div = primes.begin(); div != primes.end(); ++div) {
//if ((i % *div) == 0) {
// takes 356 seconds
for (int iter = 0; iter < primes.size(); ++iter) {
if ((i % primes[iter]) == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
primes.push_back(i);
std::cout << i << " ";
}
}
std::cout << "generating prime numbers up to " << x << " took " <<
round(static_cast<std::chrono::duration<double>>((std::chrono::high_resolution_clock::now() - starttime)).count())
<< " seconds.";
}
its because of usage vector<unsinged int> for third method.
especially primes.push_back which leads to allocations. Try to primes.reserve initially
I'd say the main issue is that most frequently a number is divisible by 2 and thus it isn't prime. I suppose the first method is more friendly with compiler and cache. But it is hard to tell for sure. Also, try to remove printing and test for time spent. Printing tends to slow the code a lot depending on usage.
A standart method for determining all prime numbers (there are more efficient ones but this one is fairly simple).
Create vector A of boolean that will indicate whether the number is prime or not. But at start set all variables to true - except A[0]=A[1]=false.
Run for loop from i = 2 to x. If A[i] is false then skip it - i is not prime. If A[i] is true then i is prime and set all A[i*k] to false for all 1<k<x/i.
This should be more efficient either of the methods.

Dividing an even number in the most efficient way

I need a program in c++ that gets a number:
LOOP:
If that number is even divide it by 2 (n=n/2)
If it's not even you can do one of this operations:
n+1
n-1
LOOP ENDS
The program should do this until n=1.
But it should do this in the most efficient and fastest way and the only hint I have is that I can use DP approach.
And the output should be numbers of operations used to calculate that number.
For example:
15->16->8->4->2->1 output:5
35->36->18->9->8->4->2->1 output:7
here's the code I wrote but it's not completed yet and it's wrong since I couldn't figure out how should I add or subtract in each step:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int n;
int h=0;
int i=0;
cout<<"Enter A Number:";
cin >> n;
int r=n;
int q=n;
cout<<r;
L1: while ( r % 2 == 0)
{
for(int m=0;r>1 && m==0 ;)
{ r=r / 2;h++;
m=r%2;
cout<<" => "<<r;
}}
while(r%2==1 && r>1)
{r=r-1;cout<<" => "<<r;h++;
goto L1;}
cout<<endl;
//**********************
cout<<q;
L2: while ( q % 2 == 0)
{
for(int m=0;q>1 && m==0 ;)
{ q=q / 2;i++;
m=q%2;
cout<<" => "<<q;
}}
while(q%2==1 && q>1)
{q=q+1;cout<<" => "<<q;i++;
goto L2;}
cout<<endl<<"First:"<<h<<endl<<"Second:"<<i<<endl;
system("pause");
}
If you want to solve it using DP:
I would state this: for each possible value 1 <=i < N find the optimal number of steps.
We use a priority queue to do this where we extract at each iteration the highest number. This is much more efficient than a vector of length N because a lot of states are unreachable (e.g. i=10 in the 15 example).
Consider that the starting state is (15,0): 15 with zero moves.
From this you create two new states (8,2) and (7,2) because for each you need two steps(add/subtract + division).
Extracting (8,2): (7,2)(4,3)
Extracting (7,2): (4,3)(3,4) Here comes DP! (7,2) would create the state (4,4) but you mantain in the queue only the minimum number of steps for the same state.
Extracting (4,3): (2,4)(3,4)
extracting(3,4): (2,4)(1,6)
Extracting (2,4): (1,5)
And that is it the solution is 5 steps.
Steps for 35:
(35,0) --- >(18,2) (17,2) -----> (17,2) (9,3) ----->
(9,3)(8,4) ----> (8,4)(5,5)(4,5) ----> (5,5)(4,5) ----->
(4,5)(3,7)(2,7)----> (3,7)(2,6) -----> (2,6)(1,9) ----> (1,7)
Solution: 7 steps.
Look if that helps you.
// Example program
#include <iostream>
#include <string>
int f (int n)
{
int iterations = 0;
while (n > 1)
{
if (n % 2 != 0)
{
std::cout << n << "->";
++n;
if (n & (n - 1))
n -= 2;
++iterations;
}
std::cout << n << "->";
n >>= 1;
++iterations;
}
std::cout << n << "->";
return iterations;
}
int main()
{
std::cout << f(15) << std::endl;
std::cout << f(41) << std::endl;
std::cout << f(43) << std::endl;
}
For use of dynamic programming, you should make recursion to get sub-solutions to the problem and then solve the problem itself. You also have to use a memory structure to hold the results of such sub-solutions.
#include <deque>
#include <iostream>
using namespace std;
int solve(deque<int>& solution, int number) {
if(number >= solution.size()) // resize to fit
solution.resize(number + 1, -1);
if(number == 1) // special case for number 1
return solution[number] = 0;
if(solution[number] != -1) // if already calculated
return solution[number];
if(number % 2 == 0) // n=n/2
return solution[number] = solve(solution, number/2) + 1;
int solutionA = solve(solution, number + 1); // n++
int solutionB = solve(solution, number - 1); // n--
return solution[number] = std::min(solutionA, solutionB) + 1; // best of n++,n--
}
int main() {
deque<int> solution;
cout << solve(solution, 35);
}
I'm not sure the code will work though.
Here's my recursive solution, verified up to 2097152 against the DP example.
The basis of it is using the value of the last two bits to determine the optimal operation. If the last bit is a 0, we always divide. If the last two bits are 11 we always increment as this transforms to 100 which enables two consecutive divide operations.
If the last two bits are 01 we decrement as this gives our next operation two consecutive divide operations vs incrementing which gives us 10.
The corner case is the number 3 where 3 -> 2 is desired over promotion to 4.
I suspect you can optimise this further by just scanning the bit pattern to determine the number of operations required. i.e. each zero requires a div op, and a set of ones can be changed into zeroes with a single addition.
#include <cstdint>
int solve_algorithmically(std::uint64_t number)
{
// If 1 there is nothing to do.
if (number <= 1)
return 0;
// Nasty hack to get around the case where number=3 & 3 == 3 will cause increment
if (number == 3)
return solve_algorithmically(number - 1) + 1;
// If we have an even number (0 in LSB)
if ((number & 1) == 0)
return solve_algorithmically(number / 2) + 1;
// If we have two consecutive 1's i.e. (...11) then increment as this wil give us two zeroes.
// The exception is the root case 3 where decrement wins.
if ((number & 3) == 3)
return solve_algorithmically(number + 1) + 1;
// The only other case ends last two bits = 01
return solve_algorithmically(number - 1) + 1;
}
int main() {
for (auto i = 1; i < 2097152; i++)
{
int alg = solve_algorithmically(i);
}
}

Largest Prime Factor- C++

I'm trying to find the largest prime factor of the number 600851475143. My code works for smaller numbers that I test (below 100). However when confronted with 600851475143, it returns 4370432, definitely not prime. Any ideas what could be wrong with my code?
#include <iostream>
#include <time.h>
#include <math.h>
using namespace std;
int main()
{
int num;
int largest;
int count;
cout<<"Please enter a number to have its Largest Prime Factor found"<<endl;
cin>>num;
num = 600851475143;
for (int factor = 1; factor <= num; factor++)
{
if (num % factor == 0)
{
count = 0;
for (int primetest=2; count == 0 && factor > primetest ; primetest++)
{
if (factor % primetest == 0)
count ++;
//endif
}
if (count == 0)
largest = factor;
//endif
}
}//endif
cout<<largest<<endl;
system("PAUSE");
}
num = 600851475143;
Integer overflow occurs here. The size of num is not large enough to contain the value which you've provided.
Use uint64_t.
#include <cstdint> //must include this!
uint64_t num = 600851475143;
Read this : cstdint
There are quite a few major problems with the code, so I want to show a better complete
solution. The main problem is that it has no input validation! Good code must be correct
on all inputs it does not reject. So I have now included proper reading and validation of
input. In this way you would have automatically caught the problem.
All major types need to have proper names! So I have introduce the typedef uint_type.
The compiler will also find out already at compile-time, if the input 60085147514 is
valid or not (though this now is also rejected at run-time). If the compiler warns,
then you need to use a bigger integer-type; however unsigned long is enough on all common
64-bit platforms (but not on common 32-bit platforms). If you need bigger integer types,
then now just one place has to be changed.
Your algorithm is horribly inefficient! All what is needed is to divide the number through
all factors found (as long as possible), and you are guaranteed to only encounter prime
numbers -- so no need to check for that. And also one only needs to consider factors up to
the square-root of the input. This all requires a bit of logic to think through -- see
the code.
Then your code violates the principle of locality: declare your variables where they are
needed, not somewhere else. You also included non-C++ headers, which furthermore were
not needed. The use of using-directives just obfuscates the code: you don't see anymore
where the components come from; and there is no need for them! I also introduced an
anonymous namespace, for the more prominent definitions.
Finally, I use a more compact coding-style (indentation by 2 spaces, brackets on the
same line, avoiding brackets if possible. Think about it: in this way you can see much
more at one glance, while with a bit of training it is also easier to read.
When compiled as shown, the compiler warns about largest_factor possibly used undefined.
This is not the case, and I opted here to consider that warning as empty.
Program LargestPrimeFactor.cpp:
// Compile with
// g++ -O3 -Wall -std=c++98 -pedantic -o LargestPrimeFactor LargestPrimeFactor.cpp
#include <string>
#include <iostream>
namespace {
const std::string program_name = "LargestPrimeFactor";
const std::string error_output = "ERROR[" + program_name + "]: ";
const std::string version_number = "0.1";
enum ErrorCodes { reading_error = 1, range_error = 2 };
typedef unsigned long uint_type;
const uint_type example = 600851475143; // compile-time warnings will show
// whether uint_type is sufficient
}
int main() {
uint_type number;
std::cout << "Please enter a number to have its largest prime factor found:"
<< std::endl;
std::cin >> number;
if (not std::cin) {
std::cerr << error_output << "Number not of the required unsigned integer"
" type.\n";
return reading_error;
}
if (number <= 1) {
std::cerr << error_output << "Number " << number << " has no largest prime"
" factor.\n";
return range_error;
}
const uint_type input = number;
uint_type largest_factor;
for (uint_type factor = 2; factor <= number/factor; ++factor)
if (number % factor == 0) {
largest_factor = factor;
do number /= factor; while (number % factor == 0);
}
if (number != 1) largest_factor = number;
std::cout << "The largest prime factor of " << input << " is " << largest_factor
<< ".\n";
}
And to offer a correction. Depending on your compiler you could try unsigned long and see if that could hold your answer. Try and write to cout and see if the variable holds the value you expect.
On another note, if you are trying to find the largest factor would it not be more efficient to count down from the highest possible factor?
You can declare your num variable as long long int.
long long int num;
This will avoid all the types of overflows occurring in your code!
C++ Program to find the largest prime factor of number.
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
// A function to find largest prime factor
long long maxPrimeFactors(long long n)
{
// Initialize the maximum prime factor
// variable with the lowest one
long long maxPrime = -1;
// Print the number of 2s that divide n
while (n % 2 == 0) {
maxPrime = 2;
n >>= 1; // equivalent to n /= 2
}
// n must be odd at this point
while (n % 3 == 0) {
maxPrime = 3;
n=n/3;
}
// now we have to iterate only for integers
// who does not have prime factor 2 and 3
for (int i = 5; i <= sqrt(n); i += 6) {
while (n % i == 0) {
maxPrime = i;
n = n / i;
}
while (n % (i+2) == 0) {
maxPrime = i+2;
n = n / (i+2);
}
}
// This condition is to handle the case
// when n is a prime number greater than 4
if (n > 4)
maxPrime = n;
return maxPrime;
}
// Driver program to test above function
int main()
{
long long n = 15;
cout << maxPrimeFactors(n) << endl;
n = 25698751364526;
cout << maxPrimeFactors(n);
}