
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Arranging Coins in C++
Suppose we have n coins that we want to form in a staircase shape, every k-th row must have exactly k coins. So if we have n, then we have to find the total number of full staircase rows that can be formed.
So, if the input is like 5, then the output will be 2, as using 5 coins we can make two full starecase rows, the last one needs three, but we have to remain 2 −
* ** **
This can be done directly by using this formula −
$$\frac{\sqrt{(8n+1)}-1}{2}$$
Example
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: int arrangeCoins(int n) { return (sqrt(8*(long long)n+1)-1)/2; } }; main(){ Solution ob; cout << (ob.arrangeCoins(13)); }
Input
13
Output
4
Advertisements