我有一个程序,可以将 2 个大数字相乘,作为 char 向量提供。现在我必须确保它使用 OpenMP。我遇到了嵌套循环的问题,如果我使用它们,结果不是我所期望的。我将非常感谢您的帮助。这是代码
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<string.h>
#include<omp.h>
#include<time.h>
#define MAX 100000
char * multiply(char [],char[], int manyThreads);
int main(){
//omp_set_dynamic(1);
omp_set_nested(1);
omp_set_num_threads(8);
char a[MAX];
char b[MAX];
char *c;
printf("First number : ");
scanf("%s",a);
printf("Second number : ");
scanf("%s",b);
printf("Result : ");
double start = omp_get_wtime( );
c = multiply(a,b,1);
printf("%s\n",c);
double end = omp_get_wtime( );
printf("Calculation time = %.16g\n", end - start);
return 0;
}
char * multiply(char a[],char b[], int manyThreads){
static char result[MAX];
char tempResult[MAX];
char temp[MAX];
int aLength,bLength;
int i,j,k=0,x=0,y;
long int r=0;
long sum = 0;
aLength=strlen(a)-1;
bLength=strlen(b)-1;
#pragma omp parallel if(manyThreads == 1)
{
#pragma omp for schedule(dynamic) nowait
for(i=0;i<=aLength;i++)
{
a[i] = a[i] - 48;
}
#pragma omp for schedule(dynamic) nowait
for(i=0;i<=bLength;i++)
{
b[i] = b[i] - 48;
}
}
#pragma omp parallel if(manyThreads == 1)
{
#pragma omp for schedule(dynamic)
for(i=bLength;i>=0;i--)
{
r=0;
#pragma omp parallel
{
#pragma omp for schedule(dynamic)
for(j=aLength;j>=0;j--)
{
temp[k++] = (b[i]*a[j] + r)%10;
r = (b[i]*a[j]+r)/10;
}
}
temp[k++] = r;
x++;
#pragma omp parallel
{
#pragma omp for schedule(dynamic)
for(y = 0;y<x;y++)
{
temp[k++] = 0;
}
}
}
}
k=0;
r=0;
#pragma omp parallel if(manyThreads == 1)
{
#pragma omp for schedule(dynamic)
for(i=0;i<aLength+bLength+2;i++)
{
sum =0;
y=0;
#pragma omp parallel
{
#pragma omp for schedule(dynamic)
for(j=1;j<=bLength+1;j++)
{
if(i <= aLength+j)
{
sum = sum + temp[y+i];
}
y += j + aLength + 1;
}
}
tempResult[k++] = (sum+r) %10;
r = (sum+r)/10;
}
}
tempResult[k] = r;
j=0;
#pragma omp parallel if(manyThreads == 1)
{
#pragma omp for schedule(dynamic)
for(i=k-1;i>=0;i--)
{
result[j++]=tempResult[i] + 48;
}
}
result[j]='\0';
if(result[0]==48)
{
result[0]=255;
}
return result;
}