本文實例講述了java模擬計算機的整數乘積計算功能。分享給大家供大家參考,具體如下:
計算機計算整數乘積的原理:
實現代碼:
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
|
package math; public class two { /** * fundamental method * f(n) = o(n^2) * @param a * @param b * @return */ public static int naivemul( int a, int b){ int x = 0 ; //判斷a中出現1的位置,每當出現1就將b的移位運算結果加到最終的結果中。 while (a > 0 ){ //n bits if (a% 2 == 1 ) x = x + b; //n bits a = a>> 1 ; b = b<< 1 ; } return x; } public static void main(string [] args){ system.out.println( "服務器之家測試結果:" ); system.out.println(naivemul( 20 , 60 )); } } |
運行結果:
希望本文所述對大家java程序設計有所幫助。
原文鏈接:http://blog.csdn.net/baidu_22502417/article/details/46416759