C++ solution to Project Euler Problem 3

Problem 3:

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?

Running time: Unknown, never finishes

Assessment: Brute forced, naive, ugly, doesn’t finish. It was really hard to post this as-is without self-editing to make me look less like a nub, but the point of posting these is to show the evolution of thought processes and problem-solving over time.

The answer is displayed more or less right away, but the code never exits, so you’re not sure if the last answer displayed before you get annoyed and hit Ctrl-C is the correct one. (It is.) I never had the patience to let it finish, let alone measure the runtime. I would approach the problem completely differently–as you’ll see in some of the later factorization examples–if I were to re-write it today.

  1. #include <iostream>
  2. using namespace std;
  3.  
  4. long long is_prime(long long n)
  5. {
  6. 	//returns 0 if not prime, 1 if prime
  7. 	if (n % 2 == 0)
  8. 		return 0;		// is even, therefore not prime
  9. 	for (long long i = 3; i <= ((n / 2) + 1); i += 2)	// Skip all the even numbers
  10. 	{
  11. 		if (n % i == 0)
  12. 			return 0;	//not prime
  13. 	}
  14. 	return 1;
  15. }
  16.  
  17. long long find_bigprime(long long n)
  18. {
  19. 	long long factor = 0;
  20. 	for(long long i = 3; i <= n; i += 2)
  21. 	{
  22. 		if (n % i == 0)
  23. 		{
  24. 			if (is_prime(i))
  25. 			{
  26. 				factor = i;
  27. 				cout << factor << endl;
  28. 			}
  29. 		}
  30. 	}
  31. 	return factor;
  32. }
  33.  
  34. int main()
  35. {
  36. 	long long input = 600851475143;
  37. 	cout << find_bigprime(input);
  38.  
  39. 	return 0;
  40. }

2 thoughts on “C++ solution to Project Euler Problem 3

Leave a Reply

Your email address will not be published. Required fields are marked *