Dart BigInt gcd()
Syntax & Examples

BigInt.gcd() method

The `gcd` method returns the greatest common divisor of two big integers.


Syntax of BigInt.gcd()

The syntax of BigInt.gcd() method is:

 BigInt gcd(BigInt other) 

This gcd() method of BigInt returns the greatest common divisor of this big integer and other.

Parameters

ParameterOptional/RequiredDescription
otherrequiredthe other big integer to find the greatest common divisor with

Return Type

BigInt.gcd() returns value of type BigInt.



✐ Examples

1 Find GCD of Positive Numbers

In this example,

  1. We create two BigInt objects, num1 and num2, initialized with 12 and 18 respectively.
  2. We then use the gcd method to find the greatest common divisor of these numbers.
  3. We print the result to standard output.

Dart Program

void main() {
  BigInt num1 = BigInt.from(12);
  BigInt num2 = BigInt.from(18);
  BigInt result = num1.gcd(num2);
  print('GCD of 12 and 18: $result');
}

Output

GCD of 12 and 18: 6

2 Find GCD of a Negative and a Positive Number

In this example,

  1. We create two BigInt objects, num1 and num2, initialized with -8 and 24 respectively.
  2. We then use the gcd method to find the greatest common divisor of these numbers.
  3. We print the result to standard output.

Dart Program

void main() {
  BigInt num1 = BigInt.from(-8);
  BigInt num2 = BigInt.from(24);
  BigInt result = num1.gcd(num2);
  print('GCD of -8 and 24: $result');
}

Output

GCD of -8 and 24: 8

3 Find GCD of Larger Numbers

In this example,

  1. We create two BigInt objects, num1 and num2, initialized with 36 and 48 respectively.
  2. We then use the gcd method to find the greatest common divisor of these numbers.
  3. We print the result to standard output.

Dart Program

void main() {
  BigInt num1 = BigInt.from(36);
  BigInt num2 = BigInt.from(48);
  BigInt result = num1.gcd(num2);
  print('GCD of 36 and 48: $result');
}

Output

GCD of 36 and 48: 12

Summary

In this Dart tutorial, we learned about gcd() method of BigInt: the syntax and few working examples with output and detailed explanation for each example.