用Cuda求素数因子

用Cuda求素数因子,cuda,Cuda,我找不到其他关于使用Cuda求一个数的最大素因子的主题,我遇到了一些问题 #include <cuda.h> #include <math.h> #include <stdio.h> __device__ int checkFactor (long long product, long long factor) { return product % factor == 0; } __global__ void factorKernel (long long

我找不到其他关于使用Cuda求一个数的最大素因子的主题,我遇到了一些问题

#include <cuda.h>
#include <math.h>
#include <stdio.h>

__device__ int checkFactor (long long product, long long factor)
{
return product % factor == 0;
}

__global__ void factorKernel (long long product, long long limit, long long *result)
{
/******************/
/* Your code here */
/******************/

/* 1. Calculate f from thread ID    */
long long f = threadIdx.x;

/* 2. Caluclate number of thread    */
int numThreads = blockIdx.x * blockDim.x;

/* 3. While f is within limit       */
/* 4.   Check whether f is a factor */
/* 5.   If yes, write f to answer   */
/* 6.   Increment f appropriately   */

while(f < limit)
{
    if(checkFactor(product,f))
    {
        result = &f;
    }
    f += numThreads;
}

}

long long factor (long long product)
{
if (product % 2 == 0)
{
    return 2;
}
long long limit = (long long) sqrt ((double) product);

long long result = 1;
long long *dResult;

/******************/
/* Your code here */
/******************/
dim3 gridDim(256);      /* Create 256 blocks */
dim3 blockDim(256);     /* Create 256 threads per block */

/* 1. Allocate memory for dResult   */
cudaMalloc((void**) &dResult, sizeof(dResult));

/* 2. Memcpy result into dResult    */
cudaMemcpy(dResult, &result, sizeof(result), cudaMemcpyHostToDevice);

/* 3. Launch the kernel             */
factorKernel<<<gridDim, blockDim>>>(product, limit, dResult);

/* 4. Memcpy dResult back to result */
cudaMemcpy(&result, dResult, sizeof(dResult), cudaMemcpyDeviceToHost);

/* 5. Free dResult                  */   
cudaFree(dResult);

return result;
}

int main (int argc, char **argv)
{
long long product = atoll (argv [1]);   /* convert arguement to long long */
long long f = factor (product);     /* call the factor function */

if (f == 1)
{
    printf ("%ld is a prime number.\n", product);
}
else
{
    printf ("%ld has a prime factor of %ld.\n", product, f);
}
return 0;
}
这个程序要做的是检查threadIdx.x是否在计算的限制内。如果是,它将使用threadIdx.x来检查因子。如果treadIdx.x是一个因子,我想将结果设置为等于threadIdx.x,那么这将是该数字的一个素数因子

已编译的nvcc-o pfactor pfactor.cu

已执行:./pfactor 11010010001

预期结果:23

实际程序挂起


我不知道为什么程序没有停止运行。

为什么要将结果设置为对f的引用?&f将结果设置为您不想要的f地址

开关:

    result = &f;
致:


其他一般问题,你能编译CUDA的例子吗

我尝试设置result=f,但无法编译。long-long类型的错误无法设置为long-long*至于argv[1],执行时应捕获数字。/pfactor 11010010001。错误:long-long类型的值无法分配给long-long*argv[0]类型的实体实际上是说pfactor,虽然argv[1]是数字,但是gv[0]将始终是程序名,永远不会是实际参数,除非您通过exec Unix或spawn Windows更新提供自定义参数,谢谢,我不知道我写那篇文章的时候在想什么,只是有些困惑@PaulI不知道为什么程序没有停止运行。blockIdx.x*blockDim.x;不提供线程数。您启动的其中一个块的blockIdx.x值始终为零。想想看。您似乎正在尝试使用栅格跨步循环。设置f=threadIdx.x+blockDim.x*blockIdx.x,并设置numThreads=gridDim.x*blockDim.x;。你需要做出答案中建议的修正。我并不是说这可以解决代码中的所有问题。
   *result = f;