Create fucntion to find GCD of two numbers

0 votes
Can someone help me write the function to find the GCD of two numbers?
Mar 28, 2019 in Java by Diya
66 views

1 answer to this question.

0 votes

Hey @Diya, here is a code on how you can achieve this,

public class GCD { //class name is GCD
    static int gcd (int a, int b) //creating a function 
    {
        if (b==0) // if b is 0 the gcd will be a
            return a;
        else
            return gcd(b,a%b); // if b is not 0 then find the modulus and keep doing it till a%b becomes 0
    }
    public static void main(String[] args) //main method
    {
        int a =10 , b=4; //two variables
        System.out.println(gcd (a,b)); //calling the function
    }

}

Hope this helps.

answered Mar 28, 2019 by Priyaj
• 57,550 points

Related Questions In Java

0 votes
1 answer

In Java, how to find out the min/max values from array of primitive data types?

import java.util.Arrays; import java.util.Collections; import org.apache.commons.lang.ArrayUtils; public class MinMaxValue { ...READ MORE

answered Jun 12, 2018 in Java by Daisy
• 8,090 points
212 views
0 votes
0 answers

How to manage two JRadioButtons in java so that only one of them can be selected at a time?

How to manage two JRadioButtons in java ...READ MORE

Apr 21 in Java by kartik
• 20,470 points
154 views
0 votes
1 answer

How to divide a string in two parts

String s="yourstring"; boolean flag = true; for(int i=0;i<s.length();i++) { ...READ MORE

answered Apr 13, 2018 in Java by Rishabh
• 3,580 points
141 views
0 votes
2 answers

How to create a 2-D array in java?

int[][] multi = new int[5][]; multi[0] = new ...READ MORE

answered Jul 16, 2018 in Java by Daisy
• 8,090 points
140 views
0 votes
1 answer

Are arrays equivalent to objects in Java ?

Yes; the Java Language Specification writes: In the Java ...READ MORE

answered May 10, 2018 in Java by Rishabh
• 3,580 points
154 views
0 votes
1 answer

Remove objects from an array in Java?

We can use external libraries: org.apache.commons.lang.ArrayUtils.remove(java.lang.Object[] array, int ...READ MORE

answered Jun 26, 2018 in Java by scarlett
• 1,280 points
158 views
0 votes
1 answer

Performance difference of if/else vs switch statement in Java

The thing you are worried about is ...READ MORE

answered Jul 26, 2018 in Java by geek.erkami
• 2,680 points
973 views
+1 vote
3 answers

What is the syntax to declare and initialize an array in java?

You can use this method: String[] strs = ...READ MORE

answered Jul 25, 2018 in Java by samarth295
• 2,190 points
1,685 views
+2 votes
2 answers

Using while loop i want to print 10 even numbers

public class Loops { ...READ MORE

answered Dec 4, 2019 in Java by One of the Simplest ways to answer you q
13,424 views
+4 votes
1 answer

How to print the individual occurance of elements in Java?

You can use a HashMap to serve ...READ MORE

answered Dec 4, 2018 in Java by Priyaj
• 57,550 points
161 views