C++求1000以内的素数,用while for语句做,输出每行4个,怎么做????跪求

如题所述

第1个回答  2011-04-15
#include<stdio.h>
#include<math.h>
void main()
{
int x=3,i=2,count;
printf("1000以内的素数为: 2 ");
for(;x<=2000;x++)
{
for(i=2;i<=x;i++)
{
if(x%i==0)break;
}
if(i>=x)
{
printf("%-5d",x);
if(count%4==0)
printf("\n");
count++;
}

}
}本回答被提问者采纳
第2个回答  2011-04-07
,使B为根号A,当然,如果是小数将小数部分省去。也就是定义为整型。然后,让A除2,看有没有余数,如果有让2加一,直到B。如果还都有余数,则为素数。以上为基本思想。

以下为程序:

#include<iostream>
#include<csting>
using namespace std;

class num
{ private: int a;
public: num(b=0)
void seta { cout<<
第3个回答  2011-04-06
#include <stdlib.h>
#include <iostream>

class CMyOutStream
{
public:
CMyOutStream(unsigned int objectsInOneLine, char separator)
: m_objectsInOneLine(objectsInOneLine)
, m_separator(separator)
, m_count(0)
{
}

template <typename T>
CMyOutStream & operator << (const T & obj)
{
std::cout << obj;

if (++m_count < m_objectsInOneLine)
std::cout << m_separator;
else
{
m_count = 0;
std::cout << std::endl;
}

return *this;
}

private:
unsigned int m_objectsInOneLine;
char m_separator;
unsigned int m_count;
};

bool GetPrimes(int max, CMyOutStream & myOut)
{
if (max < 2)
return true;

int * flags = new int[max];
if (NULL == flags)
return false;

memset(flags, 0, (max - 1) * sizeof(int));
--flags; // 0 is never used
flags[1] = 1;

for (int i = 2; i <= max; ++i)
{
if (0 != flags[i])
continue;

// i is a prime
myOut << i;

int temp = max / i;
// flag all of the numbers whose maximum prime factor is i
for (int j = 1; j <= temp; ++j)
if (0 != flags[j])
flags[i * j] = 1;
}

delete [] (flags + 1);

return true;
}

int main()
{
GetPrimes(1000, CMyOutStream(4, '\t'));
system("pause");
return 0;
}
第4个回答  2011-04-06
mark
相似回答