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()函数用来控制输出间隔