利用减治法的思想来实现,
将2个整数相乘只需要进行简单的加法和位运算。
实现如下:
1
using
System;
2
using
System.Collections.Generic;
3
using
System.Text;
4
5
namespace
ConsoleApplication43
6
{
7
class Program
8
{
9
static void Main(string[] args)
10
{
11
ESCF e = new ESCF();
12
13
int s = e.GetResult(10, 10);
14
15
System.Console.WriteLine(s);
16
17
s = e.GetResult(1043, -1022);
18
19
System.Console.WriteLine(s);
20
}
21
}
22
23
/// <summary>
24
/// 判断一个整数是奇数还是偶数。
25
/// </summary>
26
class OddEven
27
{
28
static private int _s = 1;
29
30
static public bool IsEven(int a)
31
{
32
return ((a & _s) == 0);
33
}
34
35
static public bool IsOdd(int a)
36
{
37
return !IsEven(a);
38
}
39
}
40
41
class ESCF
42
{
43
private int _small;
44
private int _big;
45
46
private bool _minus;
47
48
private void init(int a, int b)
49
{
50
int f = 0;
51
52
if (a < 0) f++;
53
if (b < 0) f++;
54
55
if (f == 0 || f == 2) _minus = false;
56
else _minus = true;
57
58
a = Math.Abs(a);
59
b = Math.Abs(b);
60
61
_small = a <= b ? a : b;
62
_big = a > b ? a : b;
63
}
64
65
public int GetResult(int a, int b)
66
{
67
init(a, b);
68
69
int reslut = 0;
70
71
while (_small != 1)
72
{
73
if (OddEven.IsEven(_small))
74
{
75
_small >>= 1;
76
_big <<= 1;
77
}
78
else
79
{
80
_small--;
81
reslut += _big;
82
83
_small >>= 1;
84
_big <<= 1;
85
}
86
}
87
88
reslut += _big;
89
90
if (_minus)
91
reslut = -reslut;
92
93
return reslut;
94
}
95
}
96
}
97

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
