Advertisement
makispaiktis

Count the digits of squares

Jul 21st, 2020 (edited)
1,285
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.09 KB | None | 0 0
  1. '''
  2. Take an integer n (n >= 0) and a digit d (0 <= d <= 9) as an integer. Square all numbers k (0 <= k <= n) between 0 and n.
  3. Count the numbers of digits d used in the writing of all the k**2. Call nb_dig (or nbDig or ...) the function taking n and d as parameters and returning this count.
  4. #Examples:
  5. n = 10, d = 1, the k*k are 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100
  6. We are using the digit 1 in 1, 16, 81, 100. The total count is then 4.
  7. nb_dig(25, 1):
  8. the numbers of interest are
  9. 1, 4, 9, 10, 11, 12, 13, 14, 19, 21 which squared are 1, 16, 81, 100, 121, 144, 169, 196, 361, 441
  10. so there are 11 digits `1` for the squares of numbers between 0 and 25.
  11. '''
  12.  
  13. def countDigitsInN(number, d):
  14.     string1 = str(number)
  15.     string2 = str(d)
  16.     counter = 0
  17.     for ch in string1:
  18.         if ch == string2:
  19.             counter += 1
  20.     return counter
  21.  
  22. def nb_dig(n, d):
  23.     counter = 0
  24.     for k in range(n+1):
  25.         counter += countDigitsInN(k**2, d)
  26.     return counter
  27.  
  28. # MAIN FUNCTION
  29. a = nb_dig(5750, 0)
  30. b = nb_dig(11011, 2)
  31. c = nb_dig(12224, 8)
  32. d = nb_dig(11549, 1)
  33. print(a, b, c, d)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement