当前位置:网站首页>Square root of X
Square root of X
2022-07-25 22:07:00 【l'amour Хэ рутилин】
subject
Enter a value greater than or equal to 2 The integer of x, Calculate and print x What is the square root of ? Don't use Math.sqrt(x)( The result retains only integers )
The exact results are obtained by replacing the square root function with other mathematical functions , Take the integer part as the answer ;
Approximate results are obtained by mathematical methods , Directly as the answer .
Method 1 : Violence solution
package main;
import java.util.Scanner;
public class Text {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println(" Please enter a value greater than 2 The integer of ");
int x= sc.nextInt();
int ans=1;
while (true){
if(ans*ans<=x&&(ans+1)*(ans+1)>x)
break;
ans++;
}
System.out.println(ans);
}
}
advantage : Easy to understand
shortcoming : If the number entered is large , The efficiency of this method is very low .
Method 2 : Two points search
When x≥2 when , Its integer square root must be less than x/2 And greater than 0, namely 0<a<x/2. because a It must be an integer , This problem can be translated into finding a specific value in an ordered set of integers , So you can use binary search .
The lower bound of binary search is 0, The upper bound can be roughly set to x. In each step of binary search , We just need to compare the intermediate elements mid The sum of the squares of x The size of the relationship , The range of the upper and lower bounds is adjusted by comparing the results .
package main;
import java.util.Scanner;
public class Text {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println(" Please enter a value greater than 2 The integer of ");
int x= sc.nextInt();
int ans=-1;
int r=x;// Upper boundary
int l=0;// Lower boundary
while (l <= r) {// The lower boundary is larger than the upper boundary to exit the cycle
int mid = l + (r - l) / 2;// In the middle
if ((long) mid * mid <= x) {// Judge the square sum of the intermediate value x The relationship between
ans = mid;
l = mid + 1;// Change lower boundary
} else {
r = mid - 1;// Change the upper boundary
}
}
System.out.println(ans);
}
}
Method 3 : Pocket calculator algorithm
Is an exponential function exp Logarithmic function ln Instead of the square root function . We can use finite mathematical functions , Get the result we want to calculate .

package main;
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println(" Please enter a value greater than 2 The integer of ");
int x= sc.nextInt();
int ans = (int) Math.exp(0.5 * Math.log(x));
System.out.println(ans);
}
}
Method four : Newton iteration
Ideas
Newton's iteration It is a method that can be used to quickly solve the zero point of a function .
For narrative purposes , We use it c Represents the integer for which the square root is to be found . obviously ,c The square root of is a function y=x^2-c Zero point of . The conclusion is

package main;
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println(" Please enter a value greater than 2 The integer of ");
int x= sc.nextInt();
double C = x, x0 = x;
while (true) {
double xi = 0.5 * (x0 + C / x0);
if (Math.abs(x0 - xi) < 1e-7) {
break;
}
x0 = xi;
}
System.out.println((int)x0);
}
}
边栏推荐
- Redis usage details
- 什么是分区分桶?
- zigbee开发板(nxpzigbee开发)
- Redis 使用详解
- What should I do if I encounter the problem of verification code during automatic testing?
- Redis foundation 2 (notes)
- mouseEvent事件——mouse坐标描述——focus事件——input事件——节流(thorttle)——mouseWheel(滚轮事件)
- Why does redis choose single thread?
- [51Nod1676 无向图同构]无向图哈希[通俗易懂]
- How to use RS485 half duplex chip correctly
猜你喜欢

『SignalR』.NET使用 SignalR 进行实时通信初体验

After three years of software testing at Tencent, I was ruthlessly dismissed in July, trying to wake up my brother who was paddling

2022 the latest software tests eight part essay. Whether you can offer depends on how you recite it

Children's programming electronic society graphical programming level examination scratch level 1 real problem analysis (judgment question) June 2022

这次龙蜥展区玩的新花样,看看是谁的 DNA 动了?

Playwright tutorial (I) suitable for Xiaobai

The technical aspects of ByteDance are all over, but the result is still brushed. Ask HR why...

How to implement an app application to limit users' time use?

『Skywalking』. Net core fast access distributed link tracking platform

6-18漏洞利用-后门连接
随机推荐
C语言左值和右值说明[通俗易懂]
ansible+Crontab批部署巡检
Solutions to the failure of win key in ikbc keyboard
磁盘空间的三种分配方式
[Fantan] how to design a test platform?
How to implement an app application to limit users' time use?
JSP初识
【饭谈】那些看似为公司着想,实际却很自私的故事 (一:造轮子)
在进行自动化测试,遇到验证码的问题,怎么办?
Unity performance optimization direction
Collation of SQL statement exercises
EL表达式改进JSP
【饭谈】软件测试薪资层次和分段(修仙)
How to configure and use rocksdb in the flinksql environment
mouseEvent事件——mouse坐标描述——focus事件——input事件——节流(thorttle)——mouseWheel(滚轮事件)
Can I buy financial products with a revenue of more than 6% after opening an account
Dovecot set mailbox quota
sql语句练习题整理
GPON introduction and Huawei OLT gateway registration and configuration process
Nuclear power plants strive to maintain safety in the heat wave sweeping Europe