MPI求素數個數

2021-07-25 13:44:59 字數 2520 閱讀 6968

附上另乙個呼叫函式後針對乙個輸入正確**:

#include "stdafx.h"

#include "mpi.h"

#include "stdio.h"

#include "string.h"

#include "math.h"

int isprime(int n)

} return flag;

}int main(int argc, char *argv)

mpi_bcast(&a,1,mpi_int,0,mpi_comm_world);

starttime1=mpi_wtime();

for(int i=mypid*2+1; i<=a; i+=size*2) //每個程序算自己的任務,儲存在local中

mpi_reduce(&local,&sum,1,mpi_int,mpi_sum,0,mpi_comm_world);//進行歸約,就是把所有程序的local加起來,得到總的素數個數

endtime1=mpi_wtime();

t1=endtime1-starttime1;

if(mypid==0)

sum=0;

starttime2=mpi_wtime();

if(mypid==0)

endtime2=mpi_wtime();

t2=endtime2-starttime2;

printf("序列素數個數是: %d\n",sum);

printf("序列時間=%f\n",t2);

printf("加速比是:%.9f",double(t2)/double(t1));

} mpi_finalize();

return 0;

}

另附上另乙個呼叫函式後針對二個輸入正確**分奇偶數:

#include "stdafx.h"

#include "mpi.h"

#include "stdio.h"

#include "string.h"

#include "math.h"

int isprime(int n)

} return flag;

}int main(int argc, char *argv)

mpi_bcast(&a,1,mpi_int,0,mpi_comm_world);

mpi_bcast(&b,1,mpi_int,0,mpi_comm_world);

starttime1=mpi_wtime();

if(a%2==0)///並行時開始輸入a為偶數

mpi_reduce(&local,&sum,1,mpi_int,mpi_sum,0,mpi_comm_world);//進行歸約,就是把所有程序的local加起來,得到總的素數個數

if(isprime(a))

sum+=1;

} else///並行時開始輸入a為數

mpi_reduce(&local,&sum,1,mpi_int,mpi_sum,0,mpi_comm_world);//進行歸約,就是把所有程序的local加起來,得到總的素數個數

} endtime1=mpi_wtime();

t1=endtime1-starttime1;

if(mypid==0)

sum=0;

starttime2=mpi_wtime();

if(mypid==0)

if(isprime(a))

sum+=1;

}else///序列時開始輸入a為奇數

}endtime2=mpi_wtime();

t2=endtime2-starttime2;

printf("序列時間=%f\n",t2);

printf("序列素數個數是: %d\n",sum);

printf("加速比是:%.9f",double(t2)/double(t1));

} mpi_finalize();

return 0;

}

錯誤分析:

1.mpi_bcast(a,2,mpi_int,0,mpi_comm_world);

用法錯誤:本句意思是0號程序向其他程序傳送乙個型別為int的陣列a[0]和[1]的值,而廣播只能傳送乙個引數值,而不是a[0]和a[1]兩個引數值,我通過測試後個人認為,

解決方法: 

mpi_bcast(&a,1,mpi_int,0,mpi_comm_world);

mpi_bcast(&b,1,mpi_int,0,mpi_comm_world);

將你想要輸入的那兩個數分兩次廣播出去

(我想最好mpi有乙個函式直接呼叫就好了,時間問題,我沒仔細搜尋)

2.負載不平衡問題(之前硬是沒想到,以後多看書)

因為偶數除了2之外不可能是素數,這就造成了0或1之中的某個程序一直處理偶數,另外乙個一直處理奇數,而偶數很快就算完結束,等待奇數程序的那個處理完後才是最終兩個執行緒並行時間,並行實際意義上就等於了序列,所以加速比之前一直在1左右

求素數個數

我最近在leetcode上擼了乙個小演算法,雖然已經工作了五年,當看到每次 提交後排名的提公升,內心依然很有成就感。題目比較簡單,求小於n的素數個數,素數也叫質數,具有以下特點 根據上面的特點,我們還可以推斷出 依據這一點,我們可以寫出下面的實現 class solution intcount 1 ...

48 求質數 素數 個數

48 求質數 素數 個數 問題描述 求出所有的大於等於n小於等於m的質數,統計其數目。n m 輸入說明 你的程式需要從標準輸入裝置 通常為鍵盤 中讀入多組測試資料。每組一行,每行包含兩個整數n m n m都不大於20000 兩組資料之間沒有多餘的空行。在行首和行尾沒有多餘的空格。輸出說明 對每組測試...

篩素數,求區間內素數個數

問題 1525 藍橋杯 演算法提高vip 找素數 時間限制 1sec 記憶體限制 128mb 提交 1179 解決 133 題目描述 給定區間 l,r 請計算區間中素數的個數。資料規模和約定 2 l r 2147483647 r l 1000000 輸入兩個數l和r。輸出一行,區間中素數的個數。樣例...