Created
July 22, 2025 01:19
-
-
Save MurageKibicho/67615cd1be035e7376040a2f3ac24c18 to your computer and use it in GitHub Desktop.
Find the first prime factor of n
This file contains hidden or 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
int FirstPrimeFactor(int n) | |
{ | |
if(n == 0 || n == 1) | |
{ | |
return n; // 0 and 1 have no prime factors | |
} | |
if(n < 0) | |
{ | |
n = -n; // Work with absolute value | |
} | |
// Check divisibility by 2 (the only even prime) | |
if(n % 2 == 0) | |
{ | |
return 2; | |
} | |
// Check odd divisors from 3 to sqrt(n) | |
for (int i = 3; i <= sqrt(n); i += 2) | |
{ | |
if(n % i == 0) | |
{ | |
return i; // Return the first prime factor found | |
} | |
} | |
// If no divisor found, n is prime | |
return n; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment