Skip to content

Commit

Permalink
Find largest prime factor ademclk#14
Browse files Browse the repository at this point in the history
  • Loading branch information
{my committed Aug 28, 2022
1 parent c5633ca commit 32ad9c3
Showing 1 changed file with 36 additions and 15 deletions.
51 changes: 36 additions & 15 deletions challenges/C++/largest_prime_factor/largestprimefactor.cpp
Original file line number Diff line number Diff line change
@@ -1,28 +1,49 @@
#include <iostream>
#include <math.h>
#include <bits/stdc++.h>

using namespace std;
int main()

long long maxPrimeFactors(long long n)
{
long long int n = 800851475143;
long long int max = INT_MIN;

long long maxPrime = -1;

while (n % 2 == 0)
{
max = 2;
n = n / 2;
maxPrime = 2;
n >>= 1;
}

for (long long int i = 3; i <= sqrt(n); i = i + 2) // i will only iterate through odd values
while (n % 3 == 0)
{
maxPrime = 3;
n = n / 3;
}

for (int i = 5; i <= sqrt(n); i += 6)
{
while (n % i == 0)
{
max = i;
maxPrime = i;
n = n / i;
}
while (n % (i + 2) == 0)
{
maxPrime = i + 2;
n = n / (i + 2);
}
}
if (n > 2)
{
max = n;
}
cout << max << endl;

if (n > 4)
maxPrime = n;

return maxPrime;
}

int main()
{
long long n;
std::cin>>n;
std::cout << maxPrimeFactors(n) << std::endl;
}

// Time complexity: {O}(\sqrt{n})
// Auxiliary space: {O}(1)

0 comments on commit 32ad9c3

Please sign in to comment.