Implement Arithmetic Utilities: GCD, LCM, And Prime Checking

by ADMIN 61 views

Introduction

In this article, we will explore the implementation of arithmetic utility functions, specifically the Greatest Common Divisor (GCD), Least Common Multiple (LCM), and prime checking, within a Command-Line Interface (CLI) framework. This feature will extend the existing CLI parser, export the functions as library functions, and integrate them into the existing CLI workflow.

Objective

The primary objective of this feature is to provide users with the ability to perform basic numeric computations directly from the command line. This will be achieved by extending the CLI argument parser to recognize new commands, implementing and exporting three new functions, and integrating them into the existing CLI workflow.

Changes Required

1. Source File (src/lib/main.js)

To implement the arithmetic utility functions, we need to extend the CLI argument parser to recognize new commands: 'gcd', 'lcm', and 'isprime'. We will also implement and export three new functions:

  • gcd(a, b): Returns the greatest common divisor of a and b.
  • lcm(a, b): Returns the least common multiple of a and b.
  • isPrime(n): Returns true if n is a prime number, false otherwise.

When invoked with one of these commands followed by the appropriate numeric arguments, we will call the corresponding function and print the result to standard output. If an invalid command or an incorrect number of arguments is provided, we will display a helpful usage message.

// src/lib/main.js
const { parse } = require('node:cli-ux').parse;
const { Command } = require('node:commander');

const program = new Command();

program
  .name('cli-utility')
  .description('A CLI utility for performing arithmetic operations')
  .version('1.0.0')
  .option('-h, --help', 'display help for command')
  .parse(process.argv);

function gcd(a, b) {
  if (b === 0) return a;
  return gcd(b, a % b);
}

function lcm(a, b) {
  return (a * b) / gcd(a, b);
}

function isPrime(n) {
  if (n <= 1) return false;
  if (n === 2) return true;
  if (n % 2 === 0) return false;
  const sqrtN = Math.sqrt(n);
  for (let i = 3; i <= sqrtN; i += 2) {
    if (n % i === 0) return false;
  }
  return true;
}

program
  .command('gcd <a> <b>')
  .description('Calculate the greatest common divisor of two numbers')
  .action((a, b) => {
    console.log(gcd(parseInt(a), parseInt(b)));
  });

program
  .command('lcm <a> <b>')
  .description('Calculate the least common multiple of two numbers')
  .action((a, b) => {
    console.log(lcm(parseInt(a), parseInt(b)));
  });

program
  .command('isprime <n>')
  .description('Check if a number is prime')
  .action((n) => {
    console.log(isPrime(parseInt(n)));
 });

if (!program.args.length) {
  program.outputHelp();
} else {
  program.parse(process.argv);
}

2. Test File (tests/unit/main.test.js)

To ensure the correctness of the arithmetic utility functions, we will add unit tests for each function:

  • Test gcd(a, b) with various pairs of positive integers.
  • Test lcm(a, b) ensuring that lcm(a, b) * gcd(a, b) equals a * b.
  • Test isPrime(n) with known prime numbers and composite numbers.

We will also include tests that simulate CLI invocations using process.argv and verify that the output matches the expected results.

// tests/unit/main.test.js
const { test, expect } = require('@jest/globals');
const { main } = require('../src/lib/main');

test('gcd(a, b) returns the greatest common divisor of a and b', () => {
  expect(main.gcd(48, 180)).toBe(12);
});

test('lcm(a, b) returns the least common multiple of a and b', () => {
  expect(main.lcm(12, 15)).toBe(60);
});

test('isPrime(n) returns true if n is a prime number, false otherwise', () => {
  expect(main.isPrime(17)).toBe(true);
  expect(main.isPrime(18)).toBe(false);
});

test('CLI invocation with gcd command returns the correct result', () => {
  const output = require('child_process').spawnSync('node', ['src/lib/main.js', 'gcd', '48', '180']);
  expect(output.stdout.toString()).toBe('12\n');
});

test('CLI invocation with lcm command returns the correct result', () => {
  const output = require('child_process').spawnSync('node', ['src/lib/main.js', 'lcm', '12', '15']);
  expect(output.stdout.toString()).toBe('60\n');
});

test('CLI invocation with isprime command returns the correct result', () => {
  const output = require('child_process').spawnSync('node', ['src/lib/main.js', 'isprime', '17']);
  expect(output.stdout.toString()).toBe('true\n');
});

3. README File (README.md)

To document the new arithmetic utilities, we will update the README file to describe the available commands, provide example command usages, and the expected output format.

# CLI Utility

A CLI utility for performing arithmetic operations.

## Usage

### Commands

*   `gcd <a> <b>`: Calculate the greatest common divisor of two numbers.
*   `lcm <a> <b>`: Calculate the least common multiple of two numbers.
*   `isprime <n>`: Check if a number is prime.

### Example Usage

*   `node src/lib/main.js gcd 48 180`: Calculate the greatest common divisor of 48 and 180.
*   `node src/lib/main.js lcm 12 15`: Calculate the least common multiple of 12 and 15.
*   `node src/lib/main.js isprime 17`: Check if 17 is a prime number.

### Output Format

The output will be in the format of the result of the arithmetic operation.

4. Dependency File (package.json)

To ensure that the updated CLI behavior is supported by the relevant npm scripts, we will verify that the scripts are updated accordingly.

{
  "name": "cli-utility",
  "version": "1.0.0",
  "scripts": {
    "test": "jest"
  },
  "dependencies": {
    "commander": "^6.2.0",
    "cli-ux": "^6.0.0"
  }
}

Acceptance Criteria

To ensure that the feature is implemented correctly, we will test the following acceptance criteria:

  • Running node src/lib/main.js gcd 48 180 should output 12.
  • Running node src/lib/main.js lcm 12 15 should output 60.
  • Running node src/lib/main.js isprime 17 should output true (and isprime 18 should output false).
  • When provided with an invalid command or incorrect arguments, the CLI should display a clear usage/help message.
  • All new tests in tests/unit/main.test.js must pass when executed with npm test.

Introduction

In our previous article, we explored the implementation of arithmetic utility functions, specifically the Greatest Common Divisor (GCD), Least Common Multiple (LCM), and prime checking, within a Command-Line Interface (CLI) framework. In this article, we will address some frequently asked questions (FAQs) related to implementing arithmetic utilities in a CLI.

Q: What are the benefits of implementing arithmetic utilities in a CLI?

A: Implementing arithmetic utilities in a CLI provides several benefits, including:

  • Convenience: Users can perform basic numeric computations directly from the command line, without the need to write code or use external tools.
  • Efficiency: Arithmetic utilities can be executed quickly and efficiently, making them ideal for tasks that require rapid calculations.
  • Flexibility: CLI arithmetic utilities can be easily extended or modified to support additional operations or features.

Q: How do I implement the GCD function in my CLI?

A: To implement the GCD function in your CLI, you can use the following steps:

  1. Define a function that takes two integers as input and returns their GCD.
  2. Use the Euclidean algorithm to calculate the GCD.
  3. Integrate the GCD function into your CLI parser, allowing users to invoke it using a specific command (e.g., gcd).

Here's an example implementation of the GCD function in JavaScript:

function gcd(a, b) {
  if (b === 0) return a;
  return gcd(b, a % b);
}

Q: How do I implement the LCM function in my CLI?

A: To implement the LCM function in your CLI, you can use the following steps:

  1. Define a function that takes two integers as input and returns their LCM.
  2. Use the formula lcm(a, b) = (a * b) / gcd(a, b) to calculate the LCM.
  3. Integrate the LCM function into your CLI parser, allowing users to invoke it using a specific command (e.g., lcm).

Here's an example implementation of the LCM function in JavaScript:

function lcm(a, b) {
  return (a * b) / gcd(a, b);
}

Q: How do I implement the prime checking function in my CLI?

A: To implement the prime checking function in your CLI, you can use the following steps:

  1. Define a function that takes an integer as input and returns a boolean indicating whether it's prime.
  2. Use a primality test (e.g., trial division, Miller-Rabin test) to determine whether the input number is prime.
  3. Integrate the prime checking function into your CLI parser, allowing users to invoke it using a specific command (e.g., isprime).

Here's an example implementation of the prime checking function in JavaScript:

function isPrime(n) {
  if (n <= 1) return false;
  if (n === 2) return true;
  if (n % 2 === 0) return false;
  const sqrtN = Math.sqrt(n);
  for (let i = 3; i <= sqrtN; i += 2) {
    if (n % i === 0) return false;
  }
  return true;
}

Q: How do I integrate arithmetic utilities into my existing CLI parser?

A: To integrate arithmetic utilities into your existing CLI parser, you can follow these steps:

  1. Define a new command for each arithmetic utility (e.g., gcd, lcm, isprime).
  2. Implement the logic for each command, using the functions defined earlier.
  3. Integrate the new commands into your CLI parser, allowing users to invoke them using the corresponding commands.

Here's an example implementation of integrating arithmetic utilities into a CLI parser in JavaScript:

const { parse } = require('node:cli-ux').parse;
const { Command } = require('node:commander');

const program = new Command();

program
  .name('cli-utility')
  .description('A CLI utility for performing arithmetic operations')
  .version('1.0.0')
  .option('-h, --help', 'display help for command')
  .parse(process.argv);

// Define the GCD function
function gcd(a, b) {
  if (b === 0) return a;
  return gcd(b, a % b);
}

// Define the LCM function
function lcm(a, b) {
  return (a * b) / gcd(a, b);
}

// Define the prime checking function
function isPrime(n) {
  if (n <= 1) return false;
  if (n === 2) return true;
  if (n % 2 === 0) return false;
  const sqrtN = Math.sqrt(n);
  for (let i = 3; i <= sqrtN; i += 2) {
    if (n % i === 0) return false;
  }
  return true;
}

// Define the CLI commands
program
  .command('gcd <a> <b>')
  .description('Calculate the greatest common divisor of two numbers')
  .action((a, b) => {
    console.log(gcd(parseInt(a), parseInt(b)));
  });

program
  .command('lcm <a> <b>')
  .description('Calculate the least common multiple of two numbers')
  .action((a, b) => {
    console.log(lcm(parseInt(a), parseInt(b)));
  });

program
  .command('isprime <n>')
  .description('Check if a number is prime')
  .action((n) => {
    console.log(isPrime(parseInt(n)));
  });

// Parse the CLI arguments
if (!program.args.length) {
  program.outputHelp();
} else {
  program.parse(process.argv);
}

Conclusion

Implementing arithmetic utilities in a CLI provides several benefits, including convenience, efficiency, and flexibility. By following the steps outlined in this article, you can implement the GCD, LCM, and prime checking functions in your CLI and integrate them into your existing CLI parser.