Write a function that returns the square root of a number, rounded up to the nearest integer.
sqrt_and_ceiling(n)
Use the math module's sqrt and ceil functions.
sqrt_and_ceiling(16) // → 4 (sqrt is exactly 4.0)
sqrt_and_ceiling(17) // → 5 (sqrt is ~4.123, rounds up to 5)
sqrt_and_ceiling(2) // → 2 (sqrt is ~1.414, rounds up to 2)
sqrt_and_ceiling(100) // → 10
import math
def sqrt_and_ceiling(n):
return math.ceil(math.sqrt(n))
math.sqrt(n) computes the square root as a float — always a float, even for perfect squares (math.sqrt(16) is 4.0, not 4). math.ceil(x) then rounds that float up to the nearest integer, returning an actual int.
Notice the two calls compose directly: math.ceil(math.sqrt(n)) passes the result of the inner call straight into the outer one, without needing an intermediate variable. This is common once you're comfortable with a function's return value — you don't always need to name it first.
For a perfect square like 16, math.sqrt(16) is exactly 4.0, and math.ceil(4.0) is just 4 — rounding up a whole number doesn't change it. For 17, math.sqrt(17) is approximately 4.123, and math.ceil rounds that up to 5.
import math
def sqrt_and_ceiling(n):
return math.ceil(math.sqrt(n))
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.