1.从终端接收一个数,封装一个函数判断该数是否为素数
cpp
#include <stdio.h>
int pri(int num)
{
int i = 0;
for (i = 2; i < num; i++)
{
if (num % i ==0)
{
return 0;
break;
}
}
if (i == num-1)
{
return 1;
}
}
int main(void)
{
int num = 0;
int ret = 0;
scanf("%d", &num);
ret = pri(num);
if (ret)
{
printf("该数是素数!\n");
}else
{
printf("该数不是素数!\n");
}
return 0;
}
2.封装一个函数实现获得两个数的最大公约数
cpp
#include <stdio.h>
int gcd(int num1, int num2)
{
int i = 1;
int j = 1;
int cnt_1 = 0;
int cnt_2 = 0;
int n1[100] = {0};
int n2[100] = {0};
int tmp = 0;
for (i = 1; i <= num1; i++)
{
if (num1 % i == 0)
{
n1[cnt_1] = i;
cnt_1++;
}
}
for (j = 1; j <= num2; j++)
{
if (num2 % j == 0)
{
n2[cnt_2] = j;
cnt_2++;
}
}
for (i = 0; i < cnt_1-1; i++)
{
for (j = 0; j < cnt_1-1-i; j++)
{
if (n1[j] > n1[j+1])
{
tmp = n1[j];
n1[j] = n1[j+1];
n1[j+1] = tmp;
}
}
}
for (i = 0; i < cnt_2-1; i++)
{
for (j = 0; j < cnt_2-1-i; j++)
{
if (n2[j] > n2[j+1])
{
tmp = n2[j];
n2[j] = n2[j+1];
n2[j+1] = tmp;
}
}
}
for (i = cnt_1-1; i >= 0; i--)
{
for (j = cnt_2-1; j >= 0; j--)
{
if (n1[i] == n2[j])
{
return n1[i];
}
}
}
}
int main(void)
{
int num1 = 0;
int num2 = 0;
int ret = 0;
scanf("%d%d", &num1, &num2);
ret = gcd(num1, num2);
printf("最大公约数为%d\n", ret);
}
3.封装一个函数实现获得两个数的最小公倍数
cpp
#include <stdio.h>
int lcm(int num1, int num2)
{
int n1[100] = {0};
int n2[100] = {0};
int i = 0;
int j = 0;
for (i = 0; i < 100; i++)
{
n1[i] = num1 * (i+1);
}
for (i = 0; i < 100; i++)
{
n2[i] = num2 * (i+1);
}
for (i = 0; i < 100; i++)
{
for (j = 0; j < 100; j++)
{
if (n1[i] == n2[j])
{
return n1[i];
}
}
}
}
int main(void)
{
int num1 = 0;
int num2 = 0;
int ret = 0;
scanf("%d%d", &num1, &num2);
ret = lcm(num1, num2);
printf("最小公倍数为:%d\n", ret);
return 0;
}
4. 封装一个函数判断该年是否为闰年
cpp
#include <stdio.h>
int leapyear(int year)
{
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
{
return 1;
}
return 0;
}
int main(void)
{
int year = 0;
int ret = 0;
scanf("%d", &year);
ret = leapyear(year);
if (ret == 1)
{
printf("该年是闰年!\n");
}else
{
printf("该年是非闰年!\n");
}
return 0;
}