如何高效求2个整数的乘积。
利用减治法的思想来实现,
将2个整数相乘只需要进行简单的加法和位运算。
实现如下:
1using System;
2using System.Collections.Generic;
3using System.Text;
4
5namespace 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
2using System.Collections.Generic;
3using System.Text;
4
5namespace 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