Calculate the number of grains of wheat on a chessboard given that the number on each square doubles.
There once was a wise servant who saved the life of a prince. The king promised to pay whatever the servant could dream up. Knowing that the king loved chess, the servant told the king he would like to have grains of wheat. One grain on the first square of a chess board. Two grains on the next. Four on the third, and so on.
There are 64 squares on a chessboard.
Write code that shows:
Did you get the tests passing and the code clean? If you want to, these are some additional things you could try:
Then please share your thoughts in a comment on the submission. Did this experiment make the code better? Worse? Did you learn anything from it?
JavaRanch Cattle Drive, exercise 6 http://www.javaranch.com/grains.jsp
This exercise has been tested on Julia versions >=1.0.
It's possible to submit an incomplete solution so you can see how others have completed the exercise.
In [ ]:
# submit
"""Calculate the number of grains on square `square`."""
function on_square(square)
end
"""Calculate the total number of grains after square `square`."""
function total_after(square)
end
In [ ]:
using Test
# canonical data version: 1.2.0
# include("grains.jl")
@testset "beginning squares" begin
@test on_square(1) == 1
@test on_square(2) == 2
@test on_square(3) == 4
@test on_square(4) == 8
@test on_square(16) == 32768
@test on_square(32) == 2147483648
@test total_after(1) == 1
@test total_after(3) == on_square(1) + on_square(2) + on_square(3)
end
@testset "ending squares" begin
@test total_after(32) < total_after(64)
@test on_square(64) == 9223372036854775808
@test total_after(64) == 18446744073709551615
end
@testset "Invalid values" begin
@testset "Zero" begin
@test_throws DomainError on_square(0)
@test_throws DomainError total_after(0)
end
@testset "Negative" begin
@test_throws DomainError on_square(-1)
@test_throws DomainError total_after(-1)
end
@testset "Greater than 64" begin
@test_throws DomainError on_square(65)
@test_throws DomainError total_after(65)
end
end
In [ ]:
# using Pkg; Pkg.add("Exercism")
# using Exercism
# Exercism.create_submission("grains")