Square Root

Instructions

Write a program in RISC-V assembly language that computes the approximated square root of integers.

To perform read and write of data from/to the terminal, you must use the read and write syscalls (similarly to exercise 3.1, but now in assembly language)

read syscall example:

    li a0, 0  # file descriptor = 0 (stdin)
    la a1, input_address #  buffer to write the data
    li a2, 1  # size (reads only 1 byte)
    li a7, 63 # syscall read (63)
    ecall

input_address: .skip 0x10  # buffer

write syscall example:

    li a0, 1            # file descriptor = 1 (stdout)
    la a1, string       # buffer
    li a2, 19           # size
    li a7, 64           # syscall write (64)
    ecall
string:  .asciz "Hello! It works!!!\n"

Input

  • Four 4-digit decimal numbers separated by spaces (' '), followed by a newline character ('\n'). The whole input takes up 20 bytes.
    • String Format - "DDDD DDDD DDDD DDDD\n"
    • D: a decimal digit, (0-9)

Output

For each 4-digit number read, you must compute its approximate square root and write its value to STDOUT using 4-digits and each square root must be separated by a space (' ') and the last one is followed by a newline character ('\n'), so the output will also take up 20 bytes.

  • String Format - "DDDD DDDD DDDD DDDD\n"
  • D: a decimal digit, (0-9)

Examples

Test CaseInputOutput
10400 5337 2240 91660020 0073 0047 0095

Notes and Tips

  • The usage of Babylonian method with 10 iterations is recommended. Considering that we want to compute the square root of a number y, the basic idea of this method is:

    • Compute an initial guess for the square root: $$ k=\frac{y}{2} $$

    • Approximate your estimative, k, to the real value of the square root by applying the following equation:

      $$ k'=\frac{k+\frac{y}{k}}{2} $$

    • Each time the above equation is applied is considered "one iteration". For this exercise, use 10 iterations.

  • For this exercise, approximate solutions are accepted.

    • Solutions with an absolute error smaller than 10 will be considered correct.
  • Other methods to square root approximation can be used, as long as:

    • It used only integers. Floating point numbers or the RISC-V square root instruction cannot be used.
    • The approximation is as or more precise than the suggested method.
  • You can test your code using the simulator's assistant from this link.