o1-mini-2024-09-12· OpenAI
WildChat-4.8M (AI2)
Make Perfect Square Coding UNSOLVED Problem Statement You will be given a number n, you…
- User
Make Perfect Square
Coding
UNSOLVED
Problem Statement
You will be given a number n, you can add 1 to this number or subtract 1 from this number in one coin. You need to make n a perfect square with minimum coins.
Input Format
• First and the only line contains the number n.
Constraints
(1 <= n <= 10^9)
Output Format
• Output the minimum number of coins required to make the number a perfect square..
Evaluation Parameters
• Sample Input
28
A
• Sample Output
3
• Explanation
28-325 is a perfect square.
Execution time limit
4 scoconds. Give cpp answer for the above problem in a function that takes int mum as input
- Assistant
#include <cmath> #include <algorithm> // Function to find the minimum number of coins to make n a perfect square int makePerfectSquare(int n) { // Calculate the floor of the square root of n int k = static_cast<int>(std::sqrt(static_cast<double>(n))); // Compute k^2 and (k+1)^2 long long square1 = static_cast<long long>(k) * k; long long square2 = static_cast<long long>(k + 1) * (k + 1); // Calculate the differences long long diff1 = static_cast<long long>(n) - square1; long long diff2 = square2 - static_cast<long long>(n); // If n is already a perfect square if (diff1 == 0) { return 0; } // Return the minimum of the two differences return static_cast<int>(std::min(diff1, diff2)); } // Example usage #include <iostream> int main() { int n; std::cin >> n; std::cout << makePerfectSquare(n) << std::endl; return 0; }