1、辗转相除法的实现
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
int main()
{
int a = 0;
int b = 0;
int r = 0;
int temp = 0;
scanf("%d %d", &a, &b);
if (a < b)
{
temp = a;
a = b;
b = temp;
}
printf("%d", a);
r = a % b;
while(1)
{
if (r == 0)
{
printf("最大公约数是:%d\n",b);
break;
}
temp = r;
r = b % temp;
b = temp;
}
return 0;
优化
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
int main()
{
int a = 0;
int b = 0;
int r = 0;
scanf("%d %d", &a, &b);
while (a % b)
{
r = a % b;
a = b;
b = r;
}
printf("最大公约数是:%d\n", b);
return 0;
}
反思:1、辗转相除法求最大公约数的大小比较是不必的。
2、循环条件的优化。
3、变量的减少使用可以提高程序运行的速度与效率,也能提高cpu运行效率。
2、goto用法和自动关机程序等
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>
int main()
{
system("shutdown -s -t 120");
char input[] = { 0 };
again:
printf("Your computer will shutdown in 60s,please enter the correct code.\n");
scanf("%s", input);
if (strcmp(input, "iamapig") == 0)
//密码中如果含有空格就不行
{
system("shutdown -a");
}
else
{
goto again;
//C语言中goto可以指向几乎任何位置
}
return 0;
}
3、输出1~100中的素数
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>
int main()
{
int i = 0;
int j = 0;
for (i = 1; i <= 100; i+=2)//偶数不可能是素数
{
for (j = 2; j < sqrt(i); j++)
{
if (i % j == 0)
{
break;
}
}
if (i % j != 0)
{
printf("%d ", i);
}
}
return 0;
}
4、输出1000到2000中的闰年
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>
int main()
{
int y = 0;
int count = 0;
for (y = 1000; y <= 2000; y++)
{
if ((y % 4 == 0) && (y % 100 !=0 ) || (y % 400 == 0))
{
printf("%d ", y);
count++;
}
}
printf("\n%d", count);
return 0;
}