我试图用C编写一个程序,该程序找到两个数字的最小除数。我想我缺少一些基本的知识来使它正常工作,但是我不确定是什么。
#include <stdio.h>
int main(void){
int divisor = 2;
int dividend = 0;
int answer;
printf("%s", "Please enter a number we will use as a dividend.");
scanf("%d", ÷nd);
while (divisor != 0) {
answer = dividend / divisor;
if (answer == 0)
else divisor++;
}
printf("The lowest positive divisor is: ");
}
答案 0 :(得分:1)
您的代码很好,这只是您的中断条件。应该是这样的:
while (divisor != 0){
if(dividend % divisor == 0)
break;
else divisor++;
}
答案 1 :(得分:0)
问题陈述中肯定会有一些困惑:两个数字的最小除数是1
,如果数字没有共同的主除数,则可能不会有更大的除数。
要找到2个数字的最大公约数,可以使用Euclid's algorithm:
#include <stdio.h>
int main(void) {
int n1, n2;
printf("%s", "Please enter two numbers: ");
if (scanf("%d", &n1, &n2) == 2) {
int a = n1, b = n2;
while (b != 0) {
int c = a % b;
a = b;
b = c;
}
printf("gcd(%d, %d) = %d\n", n1, n2, a);
}
return 0;
}
要找到大于1
的最低除数,必须在循环中测试两个数字:
#include <stdio.h>
int main(void) {
int n1, n2;
printf("%s", "Please enter two numbers: ");
if (scanf("%d", &n1, &n2) == 2) {
int a = 2, res = 1;
for (;; a++) {
if (a > n1 / a) // no larger divisor of n1
break;
if (n1 % a != 0) // not a divisor of n1
continue;
if (a > n2 / a) // no larger divisor of n2
break;
if (n2 % a != 0) // not a divisor of n2
continue;
res = a; // found the lowest common divisor > 1
break;
}
printf("lowestcd(%d, %d) = %d\n", n1, n2, a);
}
return 0;
}