Square number-(Cow customer)

Topic: Niu Mei is a girl who likes perfect square numbers.
Every time Niu Mei sees a number x, she wants to find the perfect square number y closest to x.
Every time the hands are too troublesome, so Niu Mei hopes you can write a program to help her solve this problem.
Formally speaking, you need to find a positive integer y, so that y can be expressed as a 2 (a is a positive integer) so that the value of |xy| is the smallest. It can be proved that such y is unique.

Link: https://ac.nowcoder.com/acm/problem/205350
Source: Niuke

Input: one line, an integer x, (1≤x≤10 12 ) represents the number asked by Niu Mei.
Output: one line, an integer y, representing the perfect square number y closest to x.

Idea: The maximum number of input is 10 12 , and you need to pay attention to the use of long long int and long double. There is also the use of floor() and ceil(). Note that the return value is not a long long int, and a long long int is needed to output the squared answer.

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    
    
 long long int x,a;
 long double m;
 cin>>x;
 m=sqrt(x);
 if((m-floor(m))<(ceil(m)-m))
 {
    
    
  a=floor(m);
 }
 else {
    
    
  a=ceil(m);
 }
    cout<<a*a<<endl;
 return 0;
}

Guess you like

Origin blog.csdn.net/HT24k/article/details/107136894