-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserialEuler.c
94 lines (67 loc) · 1.83 KB
/
serialEuler.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// TotientRance.c - Sequential Euler Totient Function (C Version)
// compile: gcc -Wall -O -o TotientRange TotientRange.c
// run: ./TotientRange lower_num uppper_num
// Greg Michaelson 14/10/2003
// Patrick Maier 29/01/2010 [enforced ANSI C compliance]
// This program calculates the sum of the totients between a lower and an
// upper limit using C longs. It is based on earlier work by:
// Phil Trinder, Nathan Charles, Hans-Wolfgang Loidl and Colin Runciman
#include <stdio.h>
#include <time.h>
// hcf x 0 = x
// hcf x y = hcf y (rem x y)
long hcf(long x, long y)
{
long t;
while (y != 0) {
t = x % y;
x = y;
y = t;
}
return x;
}
// relprime x y = hcf x y == 1
int relprime(long x, long y)
{
return hcf(x, y) == 1;
}
// euler n = length (filter (relprime n) [1 .. n-1])
long euler(long n)
{
long length, i;
length = 0;
for (i = 1; i < n; i++)
if (relprime(n, i))
length++;
return length;
}
// sumTotient lower upper = sum (map euler [lower, lower+1 .. upper])
long sumTotient(long lower, long upper)
{
long sum, i;
sum = 0;
for (i = lower; i <= upper; i++)
sum = sum + euler(i);
return sum;
}
int main(int argc, char ** argv)
{
long lower, upper;
double cpu_time_used;
clock_t start, end;
if (argc != 3) {
printf("not 2 arguments\n");
return 1;
}
sscanf(argv[1], "%ld", &lower);
sscanf(argv[2], "%ld", &upper);
printf("===========================================================\n");
start = clock();
printf("\n\tC: Sum of Totients between [%ld..%ld] is %ld\n",
lower, upper, sumTotient(lower, upper));
end = clock();
cpu_time_used = (double)(end-start)/CLOCKS_PER_SEC;
printf("\n\t + Time needed for this task: %f seconds.\n\n", cpu_time_used);
printf("===========================================================\n");
return 0;
}