2

I have the following snippet of code:

public static int digPow(int n, int p) {
  int powCounter = p;
  int sum = 0;
  char[] digits = (""+n).toCharArray();

  for (char digit : digits) {
    sum += Math.pow(Character.getNumericValue(digit), powCounter);
    powCounter++;
  }

  if (sum % n == 0) return sum / n;
  else return -1;
}

I don't understand how to define the time complexity, because, even though I have a loop, it seems to me that it's not just O(n). Or it is?

Serhii Chernikov
  • 353
  • 2
  • 11
  • _it seems to me that it's not just O(n)_ why do you think so? – Sotirios Delimanolis Dec 03 '22 at 15:02
  • 2
    It's O(log n), assuming Math.pow runs in O(1) time. I'd look carefully at your accuracy though -- you return a long (suggesting the result might not fit in an int), but `sum` is an `int`, and Math.pow takes doubles (which represent all `int` values exactly, but not all `long` values). – Paul Hankin Dec 03 '22 at 15:31

1 Answers1

1

Its O(n), where n is the length of the character array digits. Since the loop will iterate that no of times the next line is a if else clause which will execute only once.

Kaushal
  • 69
  • 5