I have written a Java program to calculate the square root of a user-defined number using Newton's method. The main operations of the algo goes like that:

answer = guess - ((guess * guess - inputNumber) / (2 * guess)); 
while (Math.abs(answer * answer - inputNumber) > leniency) {
    guess = answer;
    answer = guess - ((guess * guess - inputNumber) / (2 * guess));
}

I'm now seeking to find the complexity of the algorithm (yup it's homework), and have read up from here that the time complexity of Newton's method is O(log(n) * F(x)).

However, from the above code snippet, I have interpreted the time complexity to be:

O(1+ ∑(1 to n) (1) ) = O(1+n) = O(n)

Not sure what I'm getting wrong here, but I can't seem to understand the disparity in big Os even after reading wiki's explanation.

Also, I am assuming that "complexity of algorithm" is synonymous to "time complexity". Is it right to do so?

Would really appreciate help in explaining this paradox, as I'm a newbie student with a few 'touch and go' programming modules worth of background.

Thanks in advance :)

有帮助吗?

解决方案

The problem is that you actually know nothing about n in your calculation - you don't say what it should be. When you calculate the actual error of the next iteration of the algorithm (do it!), you'll see that eg. if a is at least 1 and error is less than 1, you basically double the number of valid places every iteration. So to get p decimal places, you have to perform log(p) iterations.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top