首页
/
每日頭條
/
生活
/
c語言如何證明素數
c語言如何證明素數
更新时间:2024-05-03 23:43:58

c語言如何證明素數?C 語言素數原理/*,我來為大家科普一下關于c語言如何證明素數?下面希望有你要的答案,我們一起來看看吧!

c語言如何證明素數(C語言素數原理)1

c語言如何證明素數

C 語言素數原理

/*

學習内容:輸入一個32位的整數,打印出到該數範圍内的所有素數。

隻能被1和自身整除的數為素數

語言:C

*/

#include <iostream>//C語言中的stdio.h

#include <cmath>//C語言中的math.h

#include <climits>//C語言中的limits.h

#include <iomanip>//格式化控制輸出

using namespace std;

//判斷一個整數是否為素數

bool IsPrime(int iValue)

{

int i;

int iRoot;

iRoot = static_cast<int>(sqrt((double)iValue));//數據類型轉換

for (i = 2; i <= iRoot; i)

{

if (iValue % i == 0)

return false;

}

return true;

}

int main()

{

unsigned int i;//循環變量

unsigned iMax;//保存有符号整型的最大值 int {{2147483647:0}}

unsigned iCount = 1;// 打印輸出的時候用于控制換行顯示

cout << "輸入一個32位的整數,可以打印出到該數範圍内的所有素數。" << endl;

cout << "請輸入該數:";

while (!(cin >> iMax) || iMax < 2 || iMax > INT_MAX)//獲取用戶的輸入,保存到iMax變量中

{

cout << "輸入的值不合法,請重新輸入:";

cin.clear();//清除cin的錯誤标志位

cin.sync();//清除輸入緩存區

}

//cout << iMax << endl;

for (i = 2; i <= iMax; i)

{

if (IsPrime(i))

{

cout << setw(12) << i;//每一個素數占12個字符的寬度 setw == set width

if (iCount % 6 == 0)//每一行隻顯示6個素數

cout << endl;//換行

}

}

cout << endl;

return 0;

}

,
Comments
Welcome to tft每日頭條 comments! Please keep conversations courteous and on-topic. To fosterproductive and respectful conversations, you may see comments from our Community Managers.
Sign up to post
Sort by
Show More Comments
Copyright 2023-2024 - www.tftnews.com All Rights Reserved