Why use the Math. sqrt (I) method and the math. sqrt method?

Source: Internet
Author: User

Why use the Math. sqrt (I) method and the math. sqrt method?

Java exercise questions

Determine the number of prime numbers between 101-200 and output all prime numbers.

Public class Prime {

Public static int count = 0;

Public static void main (String [] args ){

For (int I = 101; I <200; I ++ ){
Boolean B = true;
For (int j = 2; j <= Math. sqrt (I); j ++ ){//---------------

If (I % j = 0 ){
B = false;
Break;
}
}
If (B ){
System. out. print (I + "");
Count ++;
}
}
System. out. println ("\ n prime number:" + count );
}
}

It is found that there is always a problem in the second for loop without Math. sqrt (I ).

Then I found this problem: Why should I use the Math. sqrt (I) method (return the positive square root of the correctly rounded double value )?

Because, you only need to judge this value,
For example, to judge 100, you only need to judge 10, 10*10
100 = n1 * n2, so there must be one n1 or n2 <= 10, so you only need to judge 10
Improve Efficiency

NOTE: If your personal opinion is incorrect, you can also point it out.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.