【发布时间】:2020-11-23 19:46:51
【问题描述】:
我有一个程序,它初始化一个大小为 1,000,000 的向量,然后找到其中的所有素数。质数存储在一个新向量中,然后我遍历该向量并尝试在其中找到所有快乐的数字。我正在尝试使用任务并行性在 2 个线程之间拆分工作,但是我从不返回任何输出。这是快乐数的定义快乐数是由以下过程定义的数字:从任何正整数开始,将数字替换为其数字的平方和,并重复该过程直到数字等于1(它会停留在哪里),或者它在一个不包括 1 的循环中无限循环。这个过程以 1 结尾的那些数字是快乐数字,而那些不以 1 结尾的数字是不快乐数字(或悲伤数字)。
#include <omp.h>
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include<bits/stdc++.h>
#include<vector>
#include<numeric>
using namespace std;
void funcA();
void funcB();
int squaresum(int n){
int sum=0;
while(n){
int d=n%10;
sum+=d*d;
n=n/10;
}
return sum;
}
bool ishappy(int n){
set<int> s;
s.insert(n);
while(1){
if(n==1) return true;
n=squaresum(n);
if(s.find(n)!=s.end()) return false;
s.insert(n);
}
return false;
}
bool isprime(int n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
int getHappyCount(int start, int size, int& happy)
{
int holder = size;
vector<int> num(size);
for(int i=start;i<start+size;i++) num[i]=i+1;
vector<int> prime;
for(int i=0;i<holder;i++)
{
if(isprime(num[i])) prime.push_back(num[i]);
}
int count=0;
for(int i=0;i<prime.size();i++)
{
if(ishappy(prime[i])) count++;
}
#pragma omp atomic
happy += count;
}
int main()
{
int happy = 0;
#pragma omp parallel num_threads(2)
{
#pragma omp sections
{
#pragma omp section
{
(void) getHappyCount(0, 500000, happy);
printf("there are %d happy prime numbers \n", happy);
}
#pragma omp section
{
(void) getHappyCount(500000, 500000, happy);
printf("there are %d happy prime numbers \n", happy);
}
}
}
printf("there are %d happy prime numbers \n", happy);
return 0;
}
【问题讨论】:
-
您的代码是否在顺序版本中产生正确的输出?
-
我有一个可以正常运行的顺序版本,但是,我在这个版本中添加了 getHappyCount 函数,并一直在尝试从这里并行化它。
-
“我从不返回任何输出。”——你能解释一下这是什么意思吗?
-
当我说我没有得到输出时,我的意思是当代码运行时没有任何返回。所以我不确定这是否仅仅是因为 fout 语句错误/以错误的方式实现,或者我的并行化尝试完全偏离了基础。
标签: c++ vector parallel-processing openmp pragma