Computer Science, asked by YASHPRANESH, 11 months ago

Write a program in java to find the hcf of two numbers.

Answers

Answered by QGP
7
Hey There!!
Here's an HCF Program:


/* To find HCF of two numbers */

import java.io.*;

public class HCF
{
    public static void main(String args[]) throws IOException
    {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        long a,b;

        System.out.print("Enter first number: ");
        a = Long.parseLong(in.readLine());

        System.out.print("Enter second number: ");
        b = Long.parseLong(in.readLine());

        System.out.println("HCF("+a+","+b+") = "+gcd(a,b));
    }
    static long gcd(long a, long b)
    {
        while(b!=0)
        {
            long t = b;
            b = a%b;
            a = t;
        }
        return a;
    }
}



Hope it helps
Purva
Brainly Community



YASHPRANESH: can u plzz show it with for loops i mean in icse standard plzz
QGP: I do not have the "Edit" Option now. I will show you here instead:
YASHPRANESH: ok
YASHPRANESH: thank u in advance
QGP: import java.io.*;

public class HCF
{
public static void main(String args[]) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

long a,b;

System.out.print("Enter first number: ");
a = Long.parseLong(in.readLine());

System.out.print("Enter second number: ");
b = Long.parseLong(in.readLine());
for(;b!=0;)
{
long t = b;
b = a%b;
a = t;
}
System.out.println("HCF = "+a);
}

}
QGP: I removed the function and placed the for loop instead of it. A while loop would have looked better, but since you asked for "for" I went with it
YASHPRANESH: ohk thank u
YASHPRANESH: in while loop i hope all the inside loop stuffs will be same
YASHPRANESH: only the for loop will be erased ri8??
QGP: I did not understand what you asked? Can you please elaborate?
Similar questions