Euler 10

So, I'm trying to solve the tenth problem in the Euler Project. Basically, I want to sum the first 2 million prime numbers. By the way, I'm an applied mathematics student, so that's why the code is a bit weird (at least according to what my programmer friends tell me, mathematicians are the worse programmers).

The idea is to have one section which determines if a number is prime, using Fermat's small theorem (http://en.wikipedia.org/wiki/Fermat%27s_little_theorem):
1
2
3
4
5
6
7
8
9
10
11
12
int small_fermat(int n)
{
	for (int i=2; i<=n; ++i)
	{
		if (pow(i+1,i-1)=1 %i)
		{
			return 1;
		}

		else return 0;
	}
}


But then, I have a problem, that pow doesn't take int types, but I can't change the type to float because modulu doesn't take float types. So how do I resolve this issue?

Then, after that, I wanted to take the sum of all of the prime numbers, by multiplying the result of the Fermat function by the number, like so:

1
2
3
4
5
6
7
8
int sum_primes(int n)
{
	int sum=0;
	for (int i=0; i<n, i++;)
	{
		sum=sum+i*small_fermat(i);
	}
}


This part is okay, but I want some input on the code in general.

Thanks a lot!
Last edited on
But then, I have a problem, that pow doesn't take int types, but I can't change the type to float because modulu doesn't take float types. So how do I resolve this issue?


You can cast your number inside the pow() function. That way it'll preserve it's int-ness, but be a float where you need it to be.
pow(i+1,i-1)=1 %i
This doesn't just look weird. Ignoring pow()'s type requirements, it's just wrong.
1. = is the assignment operator, not the comparison operator. You can't assign to the return value of a function.
2. The expression (x==1 %y) still doesn't make sense. % has little to do with congruence from mathematics. x%y is merely the remainder of dividing x by y. (x==1%y) is equivalent to (x==(1%y)), which of course is equivalent to (x==1).
The proper way to write this check (again, ignoring pow()'s type requirements) would be (pow(i+1,i-1)%i==1).

Using Fermat's little theorem doesn't give you any advantage over, say, trial division. It's much worse, actually, because you have to test all integers in [2;n], and pow() is much slower than %.
Since you have to generate many consecutive primes, it would probably be best to use a sieve.

1
2
3
4
for (int i=0; i<n, i++;)
{
	sum=sum+i*small_fermat(i);
}
Three things:
1. Check your semicolons in the for header.
2. You're supposed to get the first 2M prime numbers, not the prime numbers below 2M.
3. The way you're getting the sum is a bit unintuitive. Most people will have to look twice before they realize what the line does. This would make sense if some numbers were "more prime" than others, and you want to get like an integer integral; or if the language didn't have decision structure. But neither of those is the case, so just do
1
2
if (is_prime(i))
    sum+=i;
Topic archived. No new replies allowed.