0

Hello I am new programer, and I need little-bit support how can I solve this simple task

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 count_factors(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)
Adam Stelmaszczyk
  • 19,665
  • 4
  • 70
  • 110
prog.Dusan
  • 1,324
  • 2
  • 12
  • 25

3 Answers3

2

Worst-case time complexity is O(sqrt(N)). Worst-case space complexity is O(1).

public class Solution
{
    public static void main(String[] args)
    {
        final Solution solution = new Solution();
        for (int i = 1; i < 25; i++)
        {
            System.out.println(i + " has " + solution.count_factors(i) + " factor(s)");
        }
    }

    public int count_factors(int N)
    {
        int result = 0;
        final int sqrtN = (int) Math.sqrt(N);
        for (int i = 1; i <= sqrtN; i++)
        {
            if (N % i == 0)
            {
                // We found 2 factors: i and N/i.
                result += 2;
            }
        }
        if (sqrtN * sqrtN == N)
        {
            // We counted sqrtN twice.
            result--;
        }
        return result;
    }
}

Output:

1 has 1 factor(s)
2 has 2 factor(s)
3 has 2 factor(s)
4 has 3 factor(s)
5 has 2 factor(s)
6 has 4 factor(s)
7 has 2 factor(s)
8 has 4 factor(s)
9 has 3 factor(s)
10 has 4 factor(s)
11 has 2 factor(s)
12 has 6 factor(s)
13 has 2 factor(s)
14 has 4 factor(s)
15 has 4 factor(s)
16 has 5 factor(s)
17 has 2 factor(s)
18 has 6 factor(s)
19 has 2 factor(s)
20 has 6 factor(s)
21 has 4 factor(s)
22 has 4 factor(s)
23 has 2 factor(s)
24 has 8 factor(s)
Adam Stelmaszczyk
  • 19,665
  • 4
  • 70
  • 110
0
 public int count_factors(int N)
 {
  int count = 2;
  for(int i=2; i<=N/2; i++)
  {
    if(N%i==0) count++;
  }
  return count;
 }

This should do it.

VishalDevgire
  • 4,232
  • 10
  • 33
  • 59
0
public int count_factors(int N) {
    int numFactors = 2; //1 and N are factors
    double sqrtN = Math.sqrt(N);
    if((sqrtN == Math.ceil(sqrtN))) //If sqrt(N) has no fractional part don't include N itself
        numFactors=1;
    for(int i=2; i <= sqrtN; i++) {
        if(N%i == 0)
            numFactors +=2; // i and N/i are factors
    }
    return numFactors;
}
halex
  • 16,253
  • 5
  • 58
  • 67