#include <stdio.h>
#include <math.h>
#define MAX_SIZE 1000 // 预定义,相当于 int MAX_SIZE = 1000;
// int gcd_b(int x, int y);
int main()
{
// printf("%d", gcd_b(121, 22));
return 0;
}
// 穷举法求最大公约数
int gcd_a(int x, int y)
{
int temp;
if (x < y)
temp = x;
else
temp = y;
while (x % temp || y % temp)
temp--;
return temp;
}
// 辗转相除法求最大公约数
int gcd_b(int x, int y)
{
int temp;
while (y)
{
temp = x % y;
x = y;
y = temp;
}
return x;
}
// 求最小公倍数
int lcm(int x, int y)
{
int temp = gcd_b(x, y);
return x * y / temp;
}
// 判断是否互质
int is_relatively_prime(int x, int y)
{
if (gcd_b(x, y) == 1)
return 1;
else
return 0;
}
// 函数递归法求斐波那契数列,容易超时
long long fib_f(int n)
{
if (n == 1 || n == 2)
return 1;
else
return fib_f(n - 1) + fib_f(n - 2);
}
// 状态转移方程求斐波那契数列,比递归快
long long fib_a(int n)
{
long long arr[MAX_SIZE] = {1, 1}; // MAX_SIZE自己根据实际情况设定
for (int i = 1; i < n; i++)
arr[i + 1] = arr[i] + arr[i - 1];
return arr[n - 1];
}
// 判断素数
int is_prime(int n)
{
if (n < 2)
return 0;
if (n == 2)
return 1;
for (int i = 2; i < sqrt(n) + 1; i++)
if (n % i == 0)
return 0;
return 1;
}
// 取整数的每一位,并返回长度
int divide_num(int n)
{
int temp, count = 0;
while (n)
{
temp = n % 10;
n /= 10;
printf("%d", temp);
count++;
}
return count;
}
// 累加
long long sum(int n)
{
long long res = 0;
for (int i = 1; i <= n; i++)
res += i;
return res;
}
// 累乘/阶乘
long long multiply(int n)
{
long long res = 1;
for (int i = 1; i <= n; i++)
res *= i;
return res;
}
/**
* 假设我们要统计字符串中,整数0~9、小写字母a~z、大写字母A~Z、以及其他字符('\0'除外)的数量
* 下面的两个实现可以之间在主函数调用,不需要再做额外的读写操作
*/
// 统计字符:一次性读入,依次取每一个字符做判断,只适合字符串中间没有空格和换行的情况
void stat_ch_once()
{
char str[MAX_SIZE]; // C语言没有字符串,只能用字符数组来实现,要数组足够大,至少要比字符串实际最大长度多1,最好是多5
scanf("%s", &str);
int count_num, count_low, count_up, count_other;
count_num = count_low = count_up = count_other = 0;
for (int i = 0; i < MAX_SIZE; i++) // char本质上就是数字,可以做相加减
if (str[i] >= '0' && str[i] <= '9')
count_num++;
else if (str[i] >= 'a' && str[i] <= 'z')
count_low++;
else if (str[i] >= 'A' && str[i] <= 'Z')
count_up++;
else if (str[i] == '\0')
break;
else
count_other++;
printf("%d %d %d %d", count_num, count_low, count_up, count_other);
}
// 统计字符:每次读入一个字符,做一次判断,空格和换行也会被读取,但是要特别小心count_other的值,通常需要手动修正
void stat_ch_more()
{
char ch;
int count_num, count_low, count_up, count_other;
count_num = count_low = count_up = count_other = 0;
// 需要判断什么时候结束输入,可以自行定义,这里是按Enter后再按Ctrl+Z结束,最终count_other会多1,因为Enter代表的'\n'也被算进去了
while (scanf("%c", &ch) != EOF)
{
if (ch >= '0' && ch <= '9')
count_num++;
else if (ch >= 'a' && ch <= 'z')
count_low++;
else if (ch >= 'A' && ch <= 'Z')
count_up++;
else if (ch == '\0')
break;
else
count_other++;
}
printf("%d %d %d %d", count_num, count_low, count_up, count_other - 1);
}
// 判断是否为闰年
int is_leap_year(int n)
{
int flag = 0;
if (year % 400 == 0)
flag = 1;
if (year % 4 == 0 && year % 100 != 0)
flag = 1;
return flag;
}
C语言初学者常用代码片段
于 2023-05-02 19:47:42 首次发布