Codility---CountFactors

Posted Hugh

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Codility---CountFactors相关的知识,希望对你有一定的参考价值。

Task description

A positive integer D is a factor of a positive integer N if there exists an integer M such that N = D * M.

For example, 6 is a factor of 24, because M = 4 satisfies the above condition (24 = 6 * 4).

Write a function:

class Solution { public int solution(int N); }

that, given a positive integer N, returns the number of its factors.

For example, given N = 24, the function should return 8, because 24 has 8 factors, namely 1, 2, 3, 4, 6, 8, 12, 24. There are no other factors of 24.

Assume that:

  • N is an integer within the range [1..2,147,483,647].

Complexity:

  • expected worst-case time complexity is O(sqrt(N));
  • expected worst-case space complexity is O(1).

 

Solution
 
Programming language used: Java
Code: 15:02:17 UTC, java, final, score:  100
// you can also use imports, for example:
// import java.util.*;

// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");

class Solution {
    public int solution(int N) {
        // write your code in Java SE 8
        int count = 0, i=1;
        double max = Math.sqrt(N);
        for(; i < max; i++) {
            if(N % i ==0) {
                count += 2;
            }
        }
        if(i*i == N){
            count++;
        }
        return count;
    }
}


https://codility.com/demo/results/training5YTT4B-5NP/

 

以上是关于Codility---CountFactors的主要内容,如果未能解决你的问题,请参考以下文章

在区分源代码,对象代码,汇编代码和机器代码时,我有一个困惑

Java中普通代码块,构造代码块,静态代码块区别及代码示例

Java中普通代码块,构造代码块,静态代码块区别及代码示例2 构造代码块

Java中普通代码块,构造代码块,静态代码块区别及代码示例2 构造代码块

上古卷轴5代码

低代码究竟是啥?