THINK FIRST·CODE LATER

← All labs

A utility class: MathTools

Problem

Write a utility class MathTools: declared final, with a private constructor (nobody can create an object), and only static methods:

  • boolean isPrime(long n) (trial division up to √n),
  • long gcd(long a, long b) (Euclid; works with negatives),
  • long power(long base, int exp) by repeated squaring (no Math.pow),
  • int clamp(int value, int low, int high),
  • double roundTo(double value, int decimals).

MathToolsApp.main reads queries until the end of input: prime 97, gcd 84 -36, pow 3 13, clamp 150 0 100, round 3.14159 2, and prints e.g. power(3, 13) = 1594323. Unknown words print unknown operation ….

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

l12-3-data-1.txt

prime 97 prime 1 prime 91 gcd 84 -36
What your program must print for l12-3-data-1.txt
isPrime(97) = true
isPrime(1) = false
isPrime(91) = false
gcd(84, -36) = 12

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < l12-3-data-1.txt

Windows PowerShell does not understand <:

Get-Content l12-3-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.