This documentation is automatically generated by online-judge-tools/verification-helper

:warning: spec/math/sqrt_digits10_spec.cr

Depends on

Code

require "spec"
require "big"
require "../../src/math/sqrt_digits10"

private def check(x, scale, d1, d2)
  Math.sqrt_digits10(x, scale).should eq({d1, d2})
end

describe Math do
  it "sqrt_digits10" do
    check 0, 10, [] of Int32, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    check 1, 10, [1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    check 2, 10, [1], [4, 1, 4, 2, 1, 3, 5, 6, 2, 3]
    check 3, 10, [1], [7, 3, 2, 0, 5, 0, 8, 0, 7, 5]
    check 123456789, 0, [1, 1, 1, 1, 1], [] of Int32
    check Int32::MAX, 5, [4, 6, 3, 4, 0], [9, 5, 0, 0, 0]
    check Int64::MAX, 5, [3, 0, 3, 7, 0, 0, 0, 4, 9, 9], [9, 7, 6, 0, 4]
    x = (1..9).to_a * 64
    check x.join.to_big_i**2, 0, x, [] of Int32
    expect_raises(ArgumentError) { Math.sqrt_digits10(0, -1) }
    expect_raises(ArgumentError) { Math.sqrt_digits10(-1, 0) }
  end
end
require "spec"
require "big"
# require "../../src/math/sqrt_digits10"
require "big"

module Math
  def sqrt_digits10(x : Int, scale : Int) : {Array(Int32), Array(Int32)}
    raise ArgumentError.new unless x >= 0
    raise ArgumentError.new unless scale >= 0

    a, b = BigInt.zero, BigInt.zero

    # TODO: use Int.digits
    digits100 = [] of typeof(x)
    while x > 0
      digits100 << x % 100
      x //= 100
    end

    integer_digits = [] of Int32
    digits100.reverse_each do |d|
      a = a * 100 + d
      k = (0..9).reverse_each.find { |k| (b * 10 + k) * k <= a }.not_nil!
      integer_digits << k
      a -= (b * 10 + k) * k
      b = b * 10 + k * 2
    end

    decimal_digits = [] of Int32
    scale.times do
      a *= 100
      k = (0..9).reverse_each.find { |k| (b * 10 + k) * k <= a }.not_nil!
      decimal_digits << k
      a -= (b * 10 + k) * k
      b = b * 10 + k * 2
    end

    {integer_digits, decimal_digits}
  end
end

private def check(x, scale, d1, d2)
  Math.sqrt_digits10(x, scale).should eq({d1, d2})
end

describe Math do
  it "sqrt_digits10" do
    check 0, 10, [] of Int32, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    check 1, 10, [1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    check 2, 10, [1], [4, 1, 4, 2, 1, 3, 5, 6, 2, 3]
    check 3, 10, [1], [7, 3, 2, 0, 5, 0, 8, 0, 7, 5]
    check 123456789, 0, [1, 1, 1, 1, 1], [] of Int32
    check Int32::MAX, 5, [4, 6, 3, 4, 0], [9, 5, 0, 0, 0]
    check Int64::MAX, 5, [3, 0, 3, 7, 0, 0, 0, 4, 9, 9], [9, 7, 6, 0, 4]
    x = (1..9).to_a * 64
    check x.join.to_big_i**2, 0, x, [] of Int32
    expect_raises(ArgumentError) { Math.sqrt_digits10(0, -1) }
    expect_raises(ArgumentError) { Math.sqrt_digits10(-1, 0) }
  end
end
Back to top page