forked from ademclk/callofcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Find largest prime factor ademclk#14
- Loading branch information
{my
committed
Aug 28, 2022
1 parent
c5633ca
commit 32ad9c3
Showing
1 changed file
with
36 additions
and
15 deletions.
There are no files selected for viewing
51 changes: 36 additions & 15 deletions
51
challenges/C++/largest_prime_factor/largestprimefactor.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |