Skip to content

Instantly share code, notes, and snippets.

@MurageKibicho
Created July 22, 2025 01:19
Show Gist options
  • Save MurageKibicho/67615cd1be035e7376040a2f3ac24c18 to your computer and use it in GitHub Desktop.
Save MurageKibicho/67615cd1be035e7376040a2f3ac24c18 to your computer and use it in GitHub Desktop.
Find the first prime factor of n
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