**Question 36 : Write a program in Java to find the Greatest Common Divisor (G.C.D.) of two numbers entered by the user :**

**Java Program :**

import java.io.*;

class hcf

{

static void main()throws IOException

{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

int a,b,i;

int d=1;

int c=0;

System.out.print("Enter the first number : ");

a=Integer.parseInt(br.readLine());

System.out.print("Enter the second number : ");

b=Integer.parseInt(br.readLine());

if (a>b)

c=a;

else

c=b;

for(i=1;i<=c;i++)

{

if (a%i==0 && b%i==0 && i>d)

d=i;

}

System.out.println("The H.C.F. = "+d);

}

}

Thanks for your program.I could not understand why

ReplyDeleted=1.If i want to take GCD of 6 and 12 then the common factors will be 1,2,3,6.WHY COMPUTER is taking 6 as answer when d=1 as i is greater than 1

This program is created to find out the largest common factor,not all the factors.

DeleteGCD = greatest common factor...simple.

Thanks for the program.

ReplyDeleteGood work but pretty tough for me to understand

ReplyDeleteUse the comment lines. Its is hard to understand for a begineer.... btw nice blog... :)

ReplyDeleteif (a%i==0 && b%i==0 && i>d) i need more ang wider explanation about this code.

ReplyDeletea%i == 0 && b%i==0 checks for common factors. i>d ensures it is not 1.but still we can skip i > d. as it is in loop so d would store the GCD

DeleteGood one but unnecessary processing.

ReplyDelete" if(a>b)

c=a;

else

c=b;

for(i=1;i<=c;i++) "

why not go from 1 to the (smaller number)/2 (instead of greater) since HCF can never be greater than half of the smaller number

"HCF can never be greater than half of the smaller number" is a wrong statement as HCF of 100 and 50 is 50.

ReplyDeletebut still why should we take greater of both . why not the smaller on

Deleteone

Deletethanks

ReplyDeleteHello... why is " if (a%i==0 && b%i==0) " used.

ReplyDeletewhat is the meaning of this statement...

Could anyone help me out????

Check my reply to the Anonymous 10 July 2013

DeleteThe condition checks if the number I divides both the numbers a and b or not ! A gcd should divide both the numbers !

Deletewithout knowing what is GCD..how can u write the code..First learn what GCD is & then try to code.

ReplyDeleteThanx for d program....its very helpful....@ blogger...

ReplyDelete