Looking for a reduced number of factors all the time complexity

In leetcode, there are many factors that need to find all integer n is a number of problems.

If the method used to take over from 1 to n to traverse to find the time complexity is O (n), in the face of some of the larger number, it will spend a lot of time.

Looking for all the factors such as n = 100, using the following codes:

public List<Integer> findFactors(int n){
		List<Integer> factors = new ArrayList<>();
		for(int i=1;i<=n;i++){
			if(n%i == 0){
				factors.add(i);
			}
		}
		return factors;
	}

At this time, the content in the body is performed 100 times.

And to think from a mathematical point of view, we can divide the limit to sqrt (n).

Obviously, sqrt (n) on the left side of each factor a, there is a necessary sqrt (n) by a factor corresponding to the right of b, so that b = n / a. In this case we just traversed 1 to 10, sufficient to determine all the factors 100:

a b
1 100
2 50
4 25
5 20
10 10

, The code can be modified based on the above ideas:

public static List<Integer> findFactors(int n){
		List<Integer> factors = new ArrayList<>();
		for(int i=1;i*i<=n;i++){
			if(n%i == 0){
				if(i*i == n){
					factors.add(i);//防止添加两个重复的因数
					break;
				}
				factors.add(i);
				factors.add(n/i);
			}
		}
		return factors;
	}

At this time, the content in the body is performed 10 times, reduced time complexity of O (√2).

In doing leetcode perfect number 507 questions, this one small change, so that the time required to pass all the test cases reduced from 1700ms to 2ms, the performance impact is evident.

Published 75 original articles · won praise 0 · Views 1503

Guess you like

Origin blog.csdn.net/qq_34087914/article/details/104124429