Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Why to use Recursion carefully when using Java to implement algorithms

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article shows you why use Java implementation algorithm with caution recursion, concise and easy to understand, absolutely can make your eyes shine, through the detailed introduction of this article I hope you can gain something.

Phenomenon:

Recursion is a very classic algorithm we achieve, can be a good description of the principle of an algorithm! Recursion is a good choice for algorithm description, performance and code structure understanding!

But what this article wants to say is that java to achieve a recursive algorithm, try not to use recursive implementation, but converted to non-recursive implementation.

Recently, when implementing a more complex algorithm, I tried it, and the non-recursive implementation can improve the speed by 1/3 compared to the recursive implementation.

Take the following simple example: (Note: For simplicity of description, only a simple example is used here)

Input parameter: N

Output result: log1 + log2 + log3 +...+ logN

The two implementation codes are as follows:

Java code

package test; public class RecursiveTest { /** * recursive implementation * * @param n * @return */ public static double recursive(long n) { if (n == 1) { return Math.log(1); } else { return Math.log(n) + recursive(n - 1); } } /** * nonrecursive realization * * @param n * @return */ public static double directly(long n) { double result = 0; for (int i = 1; i

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report