大数乘法C++实现

并行字符串乘法实现
本文介绍了一种利用多线程技术实现字符串相乘的方法,通过将任务分配给多个线程来加速运算过程。该算法适用于长字符串的乘法运算,并展示了如何使用 C++11 的标准库进行线程管理及同步。
#include <iostream>
#include <string>
#include <vector>
#include <stdlib.h>
#include <assert.h>
#include <thread>
#include <condition_variable>
#include <atomic> 
#include <chrono>

using namespace std;

const int MAX_THREADS_COUNT = 8;
unsigned long m , n;
int* tVal;

void muladd(string const& a, string const& b, int flag) {
	long pos = 0, value = 0;

	for(long i=0; i< m; i++) {
		if(i%MAX_THREADS_COUNT != flag)  continue;
		for(long j=0;j<n;j++) {
			pos = (m - 1 - i) + (n - 1 - j);
			value = (a.at(i) - '0') * (b.at(j) - '0');
			tVal[pos] += value;
		}
	}
}

string mul(string a, string b) {
    string res = "";
	
	m = a.length();
	n = b.length();
	tVal = new int[m+n];
	cout<<"m="<<m<<",n="<<n<<endl;
	for(long i=0; i< m + n; i++) {
		tVal[i] = 0;
	}
	
	std::thread* threads = new std::thread[m];
	for(int i=0; i< MAX_THREADS_COUNT; i++) {
		threads[i] = std::thread(muladd,a,b,i);
	}
	
	for(int i=0; i< MAX_THREADS_COUNT; i++) 
		threads[i].join();

	cout<<"m + n="<<m + n<<endl;	
 	for(long i=0; i< m + n; i++) {
		if(tVal[i] > 9) {
			tVal[i+1] += tVal[i]/10;
			tVal[i] %= 10;
		}
	} 
	
	for(long i=m+n-1; i>=0; i--) {
		if(tVal[i] == 0 && !res.compare("")) continue;
		res += (tVal[i] + '0');
	}

	return res;
}

int main()
{
    string a,b,c;
    cin>>a>>b;
	c=mul(a,b);
    cout<<c<<endl;
    return 0;
}

g++ -std=c++11 -pthread -o mul mul.cpp

转载于:https://my.oschina.net/d63hbz/blog/910101

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值