JavaScript: Find the greatest common divisor of two positive numbers
Question
JavaScript: Find the greatest common divisor of two positive numbers
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:
- The function
gcdtakes two parameters,aandb. - If
bis0, thenais the GCD of the two numbers. - If
bis not0, then we recursively call thegcdfunction withband the remainder ofadivided bybas the new parameters. - This process continues until
bis0, at which pointais the GCD of the original two numbers.
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.*;34public class Solution {56 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
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.