+ -
当前位置:首页 → 问答吧 → 新手C++ 一问

新手C++ 一问

时间:2014-02-28

来源:互联网

我就想USER入一个数之后将果个数之内的PRIME NUMBER SHOW出来,但系点解我写到下面果个样
我入10
佢都会出2,3,4,5,6,7,8,9,10比我,明明我都FALSE左唔系PRIME NUMBER果D,只系出TRUE
请求解答,谢谢
#include <iostream>
#include <math.h>
using namespace std;
int main()
{ int n;
cout <<"Enter the value of n: ";
cin >> n;
cout <<endl;
n=n+1;
bool* arr=new bool [n];
int checkprime=0;
int primeno=0;
for(int i=2; i<n;i++)
{
arr=true;
}
for(int a=2; a<n-2;a++)
{
for(int b=2; b<n-2;b++)
{
if(a%b==0)
{
arr[a]=true;

}
for(int c=2;c<n/2;c++)
{
int x=((n-1)/2)-1;
if(c=x*a)
arr[x]=false;
}
}
}

cout << "Prime numbers: ";
for(int i=2;i<n;i++)
{
if(arr=true)
{
cout << i <<" ";
primeno++;
}
}
cout << endl;
cout << primeno <<" primes found.";
system("pause");
return 0;

}

[ 本帖最后由 ng2b30 於 2014-2-15 03:58 PM 编辑 ]

作者: ng2b30   发布时间: 2014-02-28

用code tag包起程式码

作者: Susan﹏汪汪   发布时间: 2014-02-28

复制内容到剪贴板代码:cout << "Prime numbers: ";
for(int i=2;i<n;i++)
{
if(arr[i]=true)
{
cout << i <<" ";
primeno++;
}
}
复制内容到剪贴板代码:if(arr[i]=true)
应改为
复制内容到剪贴板代码:if(arr[i]==true)
单等号系赋值运算元(assignment operator)
双等号系比较运算元(comparison operator)

作者: Susan﹏汪汪   发布时间: 2014-02-28

复制内容到剪贴板代码:if(a%b==0)
{
arr[a]=true;

}
另外.....除唔尽的先系质数
你呢到把除得尽的set做true

之后show晒所有true的数字....即系show晒合成数

还有段code没有free memory

作者: Susan﹏汪汪   发布时间: 2014-02-28

讲起质数....汪汪之前写FFT时要做合数分解
写左个勉强可以的(至少在细数字或者有细factor的话都分解到)
复制内容到剪贴板代码:const std::map<uintmax_t, uintmax_t> Decompose(uintmax_t n)
{
static std::recursive_mutex mtx;
static std::map<uintmax_t, std::map<uintmax_t, uintmax_t>> _factors;

if(n == 0 || n == 1) throw;
std::map<uintmax_t, uintmax_t> &result = _factors[n];

//find the exists...
{
std::lock_guard<std::recursive_mutex> lck(mtx);
if(!result.empty())
return result;
}
if(n == 2)
{
std::lock_guard<std::recursive_mutex> lck(mtx);
result[2] = 1;
return result;
}

auto _decompose = [&](uintmax_t n, uintmax_t a, std::map<uintmax_t, uintmax_t> &result)
{
uintmax_t gcd = GCD(n, a);
if(gcd != 1)
{
std::lock_guard<std::recursive_mutex> lck(mtx);
for(auto q : Decompose(gcd))
{
if(result.find(q.first) == result.end())
result[q.first] = q.second;
else
result[q.first] += q.second;
}
for(auto q : Decompose(n / gcd))
{
if(result.find(q.first) == result.end())
result[q.first] = q.second;
else
result[q.first] += q.second;
}
return true;
}
return false;
};

for(auto i = _factors.begin(); i != _factors.end() && i->first != n; ++i)
{
if(_decompose(n, i->first, result)) return result;
}

if(_decompose(n, 2, result)) return result;
for(uintmax_t i = 3; i <= n / i; i += 2)
{
if(_decompose(n, i, result)) return result;
}

//write prime...
{
std::lock_guard<std::recursive_mutex> lck(mtx);
result[n] = 1;
}
return result;
}
[ 本帖最后由 Susan﹏汪汪 於 2014-2-15 08:15 PM 编辑 ]

作者: Susan﹏汪汪   发布时间: 2014-02-28

热门下载

更多