CM中的LCM和GCD使用递归或常规方法

时间:2012-12-17 23:49:42

标签: c

大家好,同时尝试从programmingsimplified进行GCD和LCM程序......我遇到了结果问题。我做的一切都是正确的(据我所知),甚至一字一句地检查,但问题仍然存在......我只是粘贴普通方法的代码。

  #include <stdio.h>

  int main()
  {
  int a, b, x, y, t, gcd, lcm;

  printf("Enter first number :");
  scanf("%d", &a);
  printf("Enter first number :");
  scanf("%d", &b);

  a = x;
  b = y;

  while (b != 0)
  {
        t = b;
        b = a % b;
        a = t;
  }

  gcd = a;
  lcm = (x * y)/gcd;

  printf("Greatest common divisior of %d and %d = %d\n", x, y, gcd);
  printf("Lowest common divisior of %d and %d = %d\n", x, y, lcm);

  getch();

  }

3 个答案:

答案 0 :(得分:3)

至少这部分是根本错误的:

int a, b, x, y, t, gcd, lcm;

printf("Enter first number :");
scanf("%d", &a);
printf("Enter first number :");
scanf("%d", &b);

a = x;
b = y;

因此,您宣布xy未初始化,然后您将其分配给ab - 现在a和{{1不包含用户输入的值,但有些垃圾。你可能想要

b

代替。

答案 1 :(得分:0)

最好试试这个。这更容易运行。

#include<stdio.h>
int GCD(int,int); 
void main(){
int p,q;
printf("Enter the two numbers: ");
scanf("%d %d",&p,&q);
printf("\nThe GCD is %d",GCD(p,q));
printf("\nThe LCM is %d",(p*q)/(GCD(p,q)));
}
int GCD(int x,int y){
if(x<y)
GCD(y,x);
if(x%y==0)
return y;
else{
GCD(y,x%y);
 }
}

答案 2 :(得分:0)

试试吧

#include<stdio.h>
int main(){
int a,b,lcm,gcd;
printf("enter two value:\n");
scanf("%d%d",&a,&b);
gcd=GCD(a,b);
lcm=LCM(a,b);
printf("LCM=%d and GCD=%d",lcm,gcd);
return 0;
}
int GCD(int a, int b){

while(a!=b){
    if(a>b){
        a=a-b;
    }else{
    b=b-a;
    }
    }
  return a;
}
int LCM(int a, int b){
return (a*b)/GCD(a,b);
}