Big integer multiplication python3 implementation

Source: Internet
Author: User

Since python has an infinite int type, it is meaningless to use python to implement the big integer multiplication, but the idea is the same. The law of exploits is that the first I-bit of the first number is multiplied by the second j-bit of the second number, and must be accumulated to the I + j-bit of the result, it starts from 0. The Code is as follows:

Import sysdef list2str (li): while li [0] = 0: del li [0] res = ''for I in li: res + = str (I) return resdef multi (stra, strb): aa = list (stra) bb = list (strb) lena = len (stra) lenb = len (strb) result = [0 for I in range (lena + lenb)] for I in range (lena): for j in range (lenb ): result [lena-i-1 + lenb-j-1] + = int (aa [I]) * int (bb [j]) for I in range (len (result)-1 ): if result [I]> = 10: result [I + 1] + = result [I] // 10 result [I] = result [I] % 10 return list2str (Result [:-1]) if _ name __= = '_ main _': if len (sys. argv )! = 3: print ('enter two parameters') exit () a = sys. argv [1] B = sys. argv [2] res = multi (a, B) print ('multi ', res) print (' OK ', int (a) * int (B ))

The multi function is the main function for multiplying large integers. The input is two large integers in the string format, and the output is the result of the string format; the list2str function converts the list containing each digit to str, and deletes the 0 value of the highest placeholder. The output result is as follows:


After multi, the result is calculated using a general big integer. After OK, the result is a multiplication result directly calculated by python itself for comparison.


Reprinted Please note:

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.