A function to find the prime factor of a number in C++


This is a very simple algorithm to find the smallest prime factor of a number:

A prime factor is a prime number by which a number is dividable. For example, 35 has two prime factors: 5 and 7.

This function finds the smallest one. For 35, it is 5. For a ngative number -m (m > 0), it is the same value evaluated for m. For 0 and 1, there is no prime factor, and this function evaluates the number itself. For a prime number, this factor is the number itself, too.

We could use this function to check if a positive number, n (n > 0), is prime or not (getPrimeFactor (n) == n && n >=2), and we could use this faction to factorize a number to its prime factors:

99 = 3 * 3 * 11

int getPrimeFactor (int n)
{
	// Don't bother to use abs () <stdlib.h>
	if (n < 0)
		n = -n;

	// For n < 2; it is just n
	if (n < 2)
		return n;

	// otherwise, for an even number it is 2
	if (n % 2 == 0)
		return 2;

	// for other odd numbers, search for a divisor
	// until SQRT (n) [conceptual] n / div >= div is
	// equivalent to SQRT (n) >= div
	for (int div = 3; n / div >= div; div += 2)
	{
		// if div is a divisor, just return it.
		if (n % div == 0)
			return div;
	}

	// There is no divisor (n is prime), return it.
	return n;
}
This entry was posted in C/C++ and tagged , , . Bookmark the permalink.

2 Responses to A function to find the prime factor of a number in C++

  1. Pingback: C++: Factorizing an Integer | 911 programming

  2. Pingback: Mixed C++/Assembly: A function to find the prime factor of a number | 911 programming

Leave a comment