Integer open Algorithm

Source: Internet
Author: User

Preface The author participated in the test of the innovation factory in 2014. He did not talk about several algorithm questions, such as heap sorting and Young's matrix. He had an algorithm for finding the integer square. At that time, he had a hard time for most of the students, I used the shift method. Later I thought about it. In fact, given the accuracy, we should use the binary approximation algorithm to calculate the square of integer N. The accuracy is in the 0.001 Train of Thought. Here we provide a variety of implementation solutions, if N is greater than 1, it starts with [1, N]. low = 1, high = N, mid = low + (high-low)> 1 start to approximate the value. If N is less than 1, it starts from [N, 1]. low = 0, high = N, mid = low + (high-low)> 1. Start to approximate the ac code.

/*** The school recruitment algorithm question of the innovative factory in 2014. The accuracy is 0.001 x/# include <stdio. h> # include <stdlib. h> # include <math. h> # define ACCURACY 0.001 double newSqrt (double n) {double low, high, mid, tmp; // obtain the upper and lower bounds if (n> 1) {low = 1; high = n;} else {low = n; high = 1;} // returns the while (low <= high) {mid = (low + high)/2.000; tmp = mid * mid; if (tmp-n <= ACCURACY & tmp-n> = ACCURACY *-1) {return mid;} else if (Tmp> n) {high = mid;} else {low = mid;} return-1.000;} int main (void) {double n, res; while (scanf ("% lf", & n )! = EOF) {res = newSqrt (n); printf ("% lf \ n", res);} return 0 ;}

 


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.