-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path13.幂函数.cpp
117 lines (106 loc) · 1.8 KB
/
13.幂函数.cpp
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
//ÇóÃݵĵݹé´úÂë
#include <stdio.h>
#include <time.h>
int powRecursionTwo(int x, int n)
{
if (0 == n)
return 1;
if (n % 2 == 1)
return powRecursionTwo(x * x, n / 2) * x;
else
return powRecursionTwo(x * x, n / 2);
}
int LoopPowerThree(int x, int n) {
int res = 1;
if (n == 0)
return (1);
for (; n > 0; n /= 3, x = x * x * x)
{
if (n % 3 == 1)
res *= x;
if (n % 3 == 2)
res *= x * x;
}
return res;
}
int LoopPowerTwo(int x, int n) {
int res = 1;
if (n == 0)
return (1);
for (; n > 0; n /= 2, x *= x)
{
if (n % 2 == 1)
res *= x;
}
return res;
}
int powRecursionThree(int x, int n)
{
if (0 == n)
return 1;
if (1 == n)
return x;
if (2 == n)
return x * x;
if (n % 3 == 1)
return powRecursionThree(x * x * x, n / 3) * x;
else if (n % 3 == 2)
return powRecursionThree(x * x * x, n / 3) * x * x;
else
return powRecursionThree(x * x * x, n / 3);
}
int powLoop(int x, int n)
{
int res = 1;
while (n > 0)
{
if (n % 2)
res *= x;
x *= x;
n /= 2;
}
return res;
}
int main()
{
clock_t beginTwo, endTwo, beginThree, endThree;
int x, n, i = 0;
int two, three;
for (int i = 0; i < 100000; i++)
{
for (int j = 0; j < 10000; j++)
{
x = i * j;
}
}
//int f = 1000;
for (int t = 0; t < 1001; t++)
{
double timeTwo = 0;
double timeThree = 0;
x = 1;
/*for (int k = -6; k < 6; k++)
{*/
n = 300 + t;
i = 0;
beginThree = clock();
for (; i < 100000; i++)
{
three = LoopPowerThree(x, n);
}
endThree = clock();
i = 0;
beginTwo = clock();
for (; i < 100000; i++)
{
two = LoopPowerTwo(x, n);
}
endTwo = clock();
timeTwo = (double)(endTwo - beginTwo) / CLOCKS_PER_SEC;
timeThree = (double)(endThree - beginThree) / CLOCKS_PER_SEC;
//}
printf("%d:", n);
printf_s("%.3f,", timeTwo);
printf_s("%.3f;", timeThree);
}
}