-5

I'm trying to answer this question:

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

What is the largest prime factor of the number 600851475143 ?

Here is my code:

#include <stdio.h>

int isPrime(long long num)
{
    for (long long k = 1; k < num; k++)
    {
            if (num%k == 0)
                    return 0;
    }

    return 1;
} 
long long num = 600851475143;
int main(void)
{
    long long prime_factor = 0;
    for (long long j = 2; j < num; j++)
    {
            if (num % j == 0 && isPrime(j) == 1)
                    prime_factor = j;
    }

    printf("%lli\n", prime_factor);


}

But for some reason it doesn't print anything, or even end. What is causing this?

2 Answers2

3

That's a terribly inefficient way of finding the prime factors of a number.

To find the prime factors, you should:

  1. Create a static list of primes less than or equal to (number / 2).
  2. Iterate over each element in the list of primes and see if each one can evenly divide the number.
  3. Divide the original number by the prime, and check the last number again.

Why? Well the smallest prime is 2. If the number isn't even then the first prime that can divide any number > 2 is 3.

Every number can be uniquely identified by its prime factors. This is called the Fundamental Theorem of Arithmetic. That means that there is only one way to represent e.g. 15 as a product of primes, in this case { 3, 5 }.

However any prime can divide a number more than once. For example, 49 is the product of two primes { 7, 7 }. Dividing the original number by one of its factors makes subsequent divisions quicker. And you can logically stop checking when the number == 1.

James T. Smith
  • 410
  • 2
  • 9
  • The first prime factor of your number is 71. Hint: There are 4. – James T. Smith Apr 22 '15 at 23:46
  • No need to go up to `(number / 2)`, up to `sqrt(number)` will suffice. – Weather Vane Apr 22 '15 at 23:52
  • I was a bit vague, sorry. I wasn't talking about finding primes. I was talking about finding the prime factors of a number. To find the prime factors of 13714, we have to check up to (13714 / 2) to find the prime factor 6857. – James T. Smith Apr 22 '15 at 23:58
  • You would have found that with the very first `2`. If you want to check for factors check `2` then iterate the odd numbers up the the square root. Beyond that you will already have checked the other factor. – Weather Vane Apr 23 '15 at 07:19
1

It doesn't print anything because it never leaves the loop, after which is found the only line which prints anything in the code. Try a smaller number and see if it ends.

SantLev
  • 140
  • 3
  • 15