當前位置:編程學習大全網 - 編程軟體 - c++編程分別用for循環和while循環找出1000到2000間的所有素數

c++編程分別用for循環和while循環找出1000到2000間的所有素數

//用for循環實現的素數查找

#include<iostream>

#include<cmath>

using namespace std;

int main(void)

{

for(int i=1001;i<10000;i++)

{

int count=0;

for(int j=2;j<=sqrt(i);j++)

{

if(i%j==0)

{

count++;

}

}

if(count==0)

{

cout<<i<<" ";

}

}

cout<<"Hello world"<<endl;

return 0;

}

//用while循環實現素數查找

int i=1000;

int line=0;//設置使得沒輸出5個素數就換行

while(i<10000)

{

int count=0;

int j=2;

while(j<=sqrt(i))

{

if(i%j==0)

{

count++;

}

j++;

}

if(count==0)

{

line++;

cout<<i<<" ";

if(line%5==0)//設置使得沒輸出5個素數就換行

{

cout<<endl;

}

}

i++;

}

  • 上一篇:為什麽我感覺現在的IT行業並不看重學歷?
  • 下一篇:零基礎的人如何成為程序員?很難嗎?
  • copyright 2024編程學習大全網