当前位置:网站首页>辗转相除、杨氏矩阵和三步翻转
辗转相除、杨氏矩阵和三步翻转
2022-07-20 09:09:00 【JDSZGLLL】
目录
引言
本文对在学习C语言过程中三个比较经典的问题,进行详细地阐述,从逻辑和代码的角度理解三个解答的细节。
辗转相除法
欧几里得算法又称辗转相除法,是指用于计算两个非负整数a,b的最大公约数。应用领域有数学和计算机两个方面。
接下来我们来看看它的实现原理:
#include <stdio.h>
int main()
{
int n = 0;
int m = 0;
scanf("%d%d", &n, &m);
//设max是最大公约数
int max = n>m?m:n;
//设min是最小公倍数
int min = n>m?n:m;
while(1)
{
if(m%max==0 && n%max ==0)
{
break;
}
max--;
}
while(1)
{
if(min%m == 0 && min%n==0)
{
break;
}
min++;
}
printf("%d\n", max+min);
return 0;
}
杨氏矩阵
杨氏矩阵是一个数字矩阵,矩阵的每行从左到右是递增的,矩阵从上到下是递增的,请编写程序在这样的矩阵中查找某个数字是否存在。
我们从图片中来观察:
#include <stdio.h>
int findnum(int a[][3], int x, int y, int f) //第一个参数的类型需要调整
{
int i = 0, j = x - 1; //从右上角开始遍历
while (j >= 0 && i < y)
{
if (a[i][j] < f) //比我大就向下
{
i++;
}
else if (a[i][j] > f) //比我小就向左
{
j--;
}
else
{
return 1;
}
}
return 0;
}
int main()
{
int a[][3] = { {1, 3, 5},
{3, 5, 7},
{5, 7, 9} }; //一个示例
if (findnum(a, 3, 3, 2))
{
printf("找到了\n");
}
else
{
printf(",没找着\n");
}
return 0;
}
三步翻转法
三步翻转法是用来解决字符串的多次左旋问题的。
实现一个函数,可以左旋字符串中的k个字符。
例如:
void reverse_part(char *str, int start, int end) //将字符串从start到end这一段逆序
{
int i, j;
char tmp;
for (i = start, j = end; i < j; i++, j--)
{
tmp = str[i];
str[i] = str[j];
str[j] = tmp;
}
}
void leftRound(char * src, int time)
{
int len = strlen(src);
int pos = time % len;
reverse_part(src, 0, pos - 1); //逆序前段
reverse_part(src, pos, len - 1); //逆序后段
reverse_part(src, 0, len - 1); //整体逆序
}
边栏推荐
- Unity学习笔记 球形全景图平面像素坐标与三维坐标系上的坐标之间的转换
- LeetCode-24-两两交换链表中的节点
- 旋转框目标检测mmrotate v0.3.1 训练HRSC2016数据集(二)
- Reading Ming Dynasty 1566
- SQL语句问题,不知道是否正确,求指导
- NepCTF
- redis 'module' 不是内部或外部命令?
- 牛客-TOP101-BM33
- ByteDance (Tiktok) software test monthly salary 23K post, technical director three interview questions are newly released
- 大佬们,这个cdc采集Oracle的数据,为啥number类型采过来就变成了对象?
猜你喜欢
随机推荐
试着换个角度理解低代码平台设计的本质
Informatics Olympiad all in one 2076: [21cspj popularization group] network | Logu p7911 [csp-j 2021] network connection
Qu'est - ce qu'une pile?
暑期总结(一)
Reading Ming Dynasty 1566
工业4.0数字孪生下的应用案例
C#入门系列(二十五) -- 接口
带你彻底认识String
Tp5.1 open the web address and output the web page code without transformation and rendering (template return $this- & gt; fetch() return view();)
链式存储结构的线性表
Redux最佳实践「Redux Toolkit」
【C语言】程序的编译(预处理)
[C language brush leetcode] 729 My schedule I (m)
Knowledge points of MySQL (11)
暑假打工 2 个 月,让我明白了 Keepalived 高可用的三种路由方案
Go method set
[postgraduate entrance examination vocabulary training camp] day 9 - vital, dynamity, previous, pray, transit, virile, invent
信息学奥赛一本通 2076:【21CSPJ普及组】网络连接(network) | 洛谷 P7911 [CSP-J 2021] 网络连接
Cloud Foundry 开发 4.cf 命令
【码蹄集新手村 600 题】如何将一个十进制整数的所有二进制的偶数位置上的二进制数值都变为 0