23、求一個整數各位數之和的函數
//求一個整數各位數之和的函數
#include<iostream>
#include<stdlib.h>
using namespace std;
int getSum(int n)
{
int sum = 0;
while(n)
{
sum = sum + n%10;
n = n/10;
}
return sum;
}
int main()
{
int x;
cin >> x;
cout << getSum(x) << endl;
system("pause");
return 0;
}
24、寫一個函數,判斷某個數是否素數,以及求1-1000以內的素數
//寫一個函數,判斷某個數是否素數,以及求1-1000以內的素數
#include<iostream>
#include<stdlib.h>
#include<math.h>
using namespace std;
//int prime_no(int n)
//{
// int count = 0;
// for(int i=1; i<(n+1); i++)
// {
// if(n%i==0) count++;
// }
// if(count == 2) cout << n << " ";
// return 0;
//}
//基本判斷思路
//在一般領域,對正整數n,如果用2到
//根號n之間的所有整數去除,均無法整除,則n爲素數。
bool isprime(int n)
{
float count = 0;
count = sqrt(float(n));
for(int i=2; i<=count; i++)
{
if(n%i==0)
return false;
//else
//return true;
}
return true;
}
int main()
{
//int x;
//cin >> x;
for(int j=1; j<1000; j++)
{
//prime_no(j);
if(isprime(j))
cout << j << " ";
}
system("pause");
return 0;
}
總結
1、素數基本判斷思路:在一般領域,對正整數n,如果用2到根號n之間的所有整數去除,均無法整除,則n爲素數。
2、sqrt()用法:sqrt(float(n))
3、setw()函數用來控制輸出間隔