Knowee
Questions
Features
Study Tools

JavaScript: Find the greatest common divisor of two positive numbers

Question

JavaScript: Find the greatest common divisor of two positive numbers

🧐 Not the exact question you are looking for?Go ask a question

Solution

Sure, here is a simple way to find the greatest common divisor (GCD) of two positive numbers in JavaScript using the Euclidean algorithm:

function gcd(a, b) {
    if (!b) {
        return a;
    }

    return gcd(b, a % b);
}

Here's how it works:

  1. The function gcd takes two parameters, a and b.
  2. If b is 0, then a is the GCD of the two numbers.
  3. If b is not 0, then we recursively call the gcd function with b and the remainder of a divided by b as the new parameters.
  4. This process continues until b is 0, at which point a is the GCD of the original two numbers.

This problem has been solved

Similar Questions

Develop a Java program to find the GCD (Greatest Common Divisor) of two numbers.Input FormatTwo integers a and b separated by a space.ConstraintsThe absolute values of a and b will be less than or equal to 10^9. a and b are non-negative integers.Output FormatA single integer representing the GCD of a and b.Sample Input 012 18Sample Output 06Contest ends in an hourSubmissions: 0Max Score: 5Difficulty: EasyRate This Challenge: More Java 151import java.io.*;2import java.util.*;3​4public class Solution {5​6    public static void main(String[] args) {7        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */8   }9}

Write a program to find out the Highest Common Factor for given two numbers.

Let's consider all integers in the range from 11 to n𝑛 (inclusive).Among all pairs of distinct integers in this range, find the maximum possible greatest common divisor of integers in pair. Formally, find the maximum value of gcd(a,b)gcd(𝑎,𝑏), where 1≤a<b≤n1≤𝑎<𝑏≤𝑛.The greatest common divisor, gcd(a,b)gcd(𝑎,𝑏), of two positive integers a𝑎 and b𝑏 is the biggest integer that is a divisor of both a𝑎 and b𝑏.InputThe first line contains a single integer t𝑡 (1≤t≤1001≤𝑡≤100)  — the number of test cases. The description of the test cases follows.The only line of each test case contains a single integer n𝑛 (2≤n≤1062≤𝑛≤106).OutputFor each test case, output the maximum value of gcd(a,b)gcd(𝑎,𝑏) among all 1≤a<b≤n1≤𝑎<𝑏≤𝑛.

Write an algorithm and draw a flowchart to find greatest common divisor and smallest common divisor of two given positive number.

Greatest Common Factor

1/2

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.