GCD function for C

前端 未结 4 1846
礼貌的吻别
礼貌的吻别 2021-02-15 18:04

Q 1. Problem 5 (evenly divisible) I tried the brute force method but it took time, so I referred few sites and found this code:

#include
int gcd(i         


        
相关标签:
4条回答
  • 2021-02-15 18:27

    This problem can also be solved in a very clean way with recursion:

    int gcd(int a, int b) {
        int remainder = a % b;
    
        if (remainder == 0) {
            return b;
        }
    
        return gcd(b, remainder);
    }
    
    0 讨论(0)
  • 2021-02-15 18:40

    Using a bit of recursion and Objective-C

    -(int)euclid:(int)numA numB:(int)numB
    {
        if (numB == 0)
            return numA;
        else
            return ([self euclid:numB numB:numA % numB]);
    }
    
    0 讨论(0)
  • 2021-02-15 18:41

    I executed this statements for GCD :

    #include<stdio.h>
    #include<conio.h>
    int main(){
       int l, s,r;
    
       printf("\n\tEnter value : ");
       scanf("%d %d",&l,&s);
    
      while(l%s!=0){
        r=l%s;
        l=s;
        s=r;
      }
      printf("\n\tGCD = %d",s);
      getch();
    }
    
    0 讨论(0)
  • 2021-02-15 18:43

    To your second question: The GCD function uses Euclid's Algorithm. It computes A mod B, then swaps A and B with an XOR swap. A more readable version might look like this:

    int gcd(int a, int b)
    {
        int temp;
        while (b != 0)
        {
            temp = a % b;
    
            a = b;
            b = temp;
        }
        return a;
    }
    
    0 讨论(0)
提交回复
热议问题