I am trying to solve a problem 3 on project euler.
For thoes who don´t know the site, here is the question I am trying to solve:

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

What is the largest prime factor of the number 600851475143 ?

And here is the code:

#include <stdio.h>
#include <stdlib.h>

#define NUMBER 13195        // Largest prime under this.

int main()
{
    int isprime = 1;
    unsigned long c, d, biggest;    // C=CURRENT number testing if prime. D=DIVIDER (tester).

    for (c = 2; c < 13195; c++) {

        isprime = 1;
        for (d = 2; d < c; d++) {

            if (d % c == 0) // I have treid c % d too.
                isprime = 0;
        }

        if (isprime == 1)
            biggest = c;
    }
    printf("%lu", biggest);

    return EXIT_SUCCESS;
}

This looks pretty strait forward to me, and I can´t see what would be wrong here.
The output is: 13194

And of course i would expect: 29. I am sorry if this is a double post of some sort, or a simple mistake I have overlooked. (I don´t have spell check on my browser at work, so sorry for that too) :)

Try this. (It works, but you'll need to adapt it a bit).

I changed d to divv, and c to cur. You need to include <math.h> for sqrt() (big time saver).

Be sure to initialize biggest to zero, before the loops start.

//two is handled separately, before this

         for (divv = 3; divv < sqroot; divv+=2) {
            if (cur % divv == 0) { // I have treid c % d too.
               isprime = 0;
               //printf("cur: %d  div: %d \n",cur, divv); getchar();
               break;
            }

         }
         if (isprime == 1) {      //is cur a factor of NUM?
            if(NUM % cur == 0 && cur > biggest) {
               biggest = cur;
               //printf("cur: %lu  div: %lu \n",cur, divv); //shows biggest cur's
            }
         }

      printf("biggest: %lu"\n,biggest);
      return 0;

Edited 4 Years Ago by Adak

This article has been dead for over six months. Start a new discussion instead.