You have n
coins and you want to build a staircase with these coins. The staircase consists of k
rows where the ith
row has exactly i
coins. The last row of the staircase may be incomplete.
Given the integer n
, return the number of complete rows of the staircase you will build.
Example 1:
Input: n = 5 Output: 2 Explanation: Because the 3rd row is incomplete, we return 2.
Example 2:
Input: n = 8 Output: 3 Explanation: Because the 4th row is incomplete, we return 3.
Constraints:
1 <= n <= 231 - 1
program main
implicit none
integer :: n, k
n = 5
k = solve(n)
write (*, '(A, I0)') 'Complete rows: ', k
n = 8
k = solve(n)
write (*, '(A, I0)') 'Complete rows: ', k
contains
function solve(n) result(k)
implicit none
integer, value :: n
integer :: i, j, k
do i = 1, n
if (mod(n, i) == 0) then
j = n / i
if (j >= i) then
k = k + 1
end if
end if
end do
end function solve
end program main
Complete rows: 1 Complete rows: 2
```
program staircase
implicit none
integer :: n, k, i
read(*,*) n
k = 0
do i = 1, n
if (i == n) then
exit
end if
if (i == n - i + 1) then
k = k + 1
end if
end do
write(*,*) k
end program staircase
```
temp.f95:1:2: 1 | ``` | 1 Error: Invalid character in name at (1) temp.f95:21:2: 21 | ``` | 1 Error: Invalid character in name at (1)
def arrange_coins(n: int) -> int:
k = 0
while n > k:
k += 1
n -= k
return k
The algorithm initializes a variable k, which represents the current row number, to 0. Then it enters a loop where it checks if n is greater than k. If so, it increments k by 1 and subtracts k from n. This process continues until n is no longer greater than k. Finally, the value of k is returned, representing the number of complete rows of the staircase. This approach has a time complexity of O(sqrt(n)) since the number of iterations increases linearly with the size of the staircase.
int arrangeCoins(int n) {
int k = 0;
while (n > k) {
k++;
n -= k;
}
return k;
}
The algorithm initializes a variable k, which represents the current row number, to 0. Then it enters a loop where it checks if n is greater than k. If so, it increments k by 1 and subtracts k from n. This process continues until n is no longer greater than k. Finally, the value of k is returned, representing the number of complete rows of the staircase. This approach has a time complexity of O(sqrt(n)) since the number of iterations increases linearly with the size of the staircase.