编程题:
寻找两个数的所有公因数
#include int main() { int num1, num2, i; printf("输入两个数,使用空格分隔:"); scanf("%d %d", &num1, &num2); for (i = 1; i <= (num1 > num2 ? num2 : num1) ; ++i) { if (num1%i == 0 && num2%i == 0) { printf("%d ", i); } } return 0; }
#include<iostream> using namespace std; void commonDivisor0(long long x1,long long x2) { static int divisor=1; if(divisor>=x1) { (x1%divisor==0 && x2%divisor==0)?cout<<divisor<<endl:cout<<endl; divisor=1; return; } if(x1%divisor==0 && x2%divisor==0) { cout<<divisor<<"\t"; } divisor++; commonDivisor0(x1,x2); } void commonDivisor(long long x1,long long x2) { x1>x2?commonDivisor0(x2,x1):commonDivisor0(x1,x2); /* long long difference=x1-x2; difference<0?-difference:difference; x1=(x1+x2-difference)/2; x2=x1+difference; commonDivisor0(x1,x2); */ } int main() { int x,y; cin>>x>>y; commonDivisor(x,y); return 0; }
#include <stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> int main(void) { int num1, num2; puts("请输入两个数字"); scanf("%d%d", &num1, &num2); for (int i = 1; i<=(num1>num2?num1:num2); i++) {//问号表达式巧用 if (num1 % i == 0 && num2 % i == 0) {//取余为0就是因子(公因子) printf("%d ", i); } } return 0; }
#include <stdio.h> int gcd(int a, int b) { //欧几里得法, 计算最大公约数 while (b != 0) { int temp = b; b = a % b; //将余数赋值给b,变成下一步的除数 a = temp; //将b最先的值赋值给a,当做下一次的被除数 } return a; } int lcm(int a, int b, int gcdValue) { // 计算最小公倍数 return a / gcdValue * b; // 先除以最大公约数,然后乘以另一个数,就能得到最下公倍数 } int main() { int num1, num2; printf("请输入两个整数:"); fflush(stdout); scanf("%d %d", &num1, &num2); int gcdValue = gcd(num1, num2); int lcmValue = lcm(num1, num2, gcdValue); printf("%d 和 %d 的最大公约数是:%d\n", num1, num2, gcdValue); printf("%d 和 %d 的最小公倍数是:%d\n", num1, num2, lcmValue); return 0; }
#include <stdi...
用户登录可进行刷题及查看答案
#include <stdio.h>
int main() { int num1, num2, i; printf("输入两个数,使用空格分隔:"); scanf("%d %d", &num1, &num2); for (i = 1; i <= (num1 > num2 ? num2 : num1) ; ++i) { if (num1%i == 0 && num2%i == 0) { printf("%d ", i); } } return 0; }
登录后提交答案