Am learning C and thought that Project Euler problems would be a fun and interesting way to learn (and would kill 2 birds with 1 stone because it would keep me thinking about maths as well) but I've hit a snag.
I have (what I think is) a good (if simple) algorithm for finding the largest prime factor of a number. It works (as far as I have tested it), but the PE question uses 600851475143 as it's final question. I have tried to use doubles and such, but I can never seem to find both a modulo and a division operator. Any help would be greatly appreciated.
Code attached is before I started to make it work with doubles (or any other type):
#include<stdio.h>
#include <math.h>
void main() {
int target, divisor, answer;
target = 375;
divisor = 2;
answer = -1;
answer = factorise (target,divisor);
printf("Answer to Euler Problem 3: %i\n", answer);
}
int factorise(number, divisor) {
int div;
while (divisor < number) {
div = divide(number,divisor);
if (div) {number = div;}
else {divisor++;}
}
return divisor;
}
int divide(a,b) {
if (a%b) {return 0;}
else {return a/b;}
}
Have you tried long
or long long
? Depending on your compiler, those might work. But you'll eventually need a bigint library for other PE problems. There are some on the internet, but since you're doing this to learn I'd suggest writing your own.