Algorithmic note _027: Russian multiplication (Java)

Source: Internet
Author: User

1 problem description

First, what is the Russian multiplication? Here, the third edition of the basics of algorithmic design and analysis is described in the text:

2 Solutions

The specific code is as follows:

 Packagecom.liuzhen.chapter4; Public classRussianpeasant {//Method 1: Recursive solution     Public voidRecursionrussian (intMintNintresult) {        if(M < 1)            return; if(M = = 1) System.out.println ("Use recursion to get m*n results:" + (result+N)); if(m% 2 = = 0) {m= M/2; N= N*2;        Recursionrussian (M,n,result); }        Else{result+=N; M= (m-1)/2; N= N*2;        Recursionrussian (M,n,result); }    }        //Method 2: Iterative solving     Public intIterationrussian (intMintN) {        intresult = 0;  while(M > 0){            if(m% 2 = = 0) {m= M/2; N= N*2; }            Else{result+=N; M= (m-1)/2; N= N*2; }        }        returnresult; }         Public Static voidMain (string[] args) {russianpeasant test=Newrussianpeasant (); Test.recursionrussian (50, 65, 0); System.out.println ("Using iterations to extract m*n results:" +test.iterationrussian (50, 65)); }}

Operation Result:

Using recursion to get m*n results: 3250 using iterations to extract m*n results: 3250

Algorithmic note _027: Russian multiplication (Java)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.