(zz)採用分治法進行大數乘法運算 (java)

來源:互聯網
上載者:User
/*************************************************************
*  此程式 採用分治法進行乘法運算
*  求 1011*1101
*  coder: 九天神龍
*  運行結果:
* H:/Java/演算法/大整數~1>javac mult.java
*
* H:/Java/演算法/大整數~1>java mult
* 11x13 結果為: 143
*
* H:/Java/演算法/大整數~1>
**************************************************************/
import java.lang.*;
class mult{

public int x,y; //本題要求積的兩個數

//初始化本題中要求的兩個數
mult(){
  x=11; //二進位的 1011
  y=13; //二進位的 1101
}

//**************************************************
// 函數名 getvalue,此函數為本演算法的主函數
// 反回值為指定數xy的積
// 根據公式 XY=A*C*2n+((A-B)(D-C)+AC+BD)*2n/2+BD
// 共有3次乘法,6次加法,2次移位
//**************************************************

public int getvalue(int a,int b,int c,int d){
  int n=4; //所求數的位元
   
  return (a*c*(2<<(n-1))+
    ((a-b)*(d-c)+a*c+b*d)*
    (2<<(n/2-1))+
    b*d);
}

public static void main(String[] args){
  int n=2;
  mult mu=new mult();
  int a,b,c,d;
  //將原乘數分解
  a=mu.x>>n;
  b=mu.x&3;
  c=mu.y>>n;
  d=mu.y&3;
 
  int ret=mu.getvalue(a,b,c,d);
   
  //output result
  System.out.println(""+mu.x+"x"+mu.y+" 結果為: "+ret);
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.