Advertisement
viking_unet

calculate count of numbers mod 3

Sep 2nd, 2020 (edited)
1,341
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.07 KB | None | 0 0
  1. # algoritm of calculate count of numbers in  
  2. # row like 1, 12, 123, 1234, .. 123456789, 12345678910, 1234567891011.. N
  3. # thats mod 3
  4.  
  5. import time
  6.  
  7. i = int(input('input N: '))
  8.  
  9. number   = 0
  10. counter  = 0
  11.  
  12. t1 = time.monotonic()
  13. for i in range(1, i+1):
  14.     # detect rank of iteration number
  15.     rank  = 1
  16.     buf_i = i
  17.     while True:
  18.         if buf_i // 10:
  19.             rank += 1
  20.             buf_i = buf_i // 10
  21.         else:
  22.             break
  23.     number = number*(10**rank) + i
  24.     # calculate sum of digits and check it mod 3
  25.     x = number
  26.     x = (x >> 16) + (x & 0xffff)
  27.     x = (x >> 10) + (x & 0x3ff)
  28.     x = (x >> 6)  + (x & 0x3f)
  29.     x = (x >> 4)  + (x & 0xf)
  30.     while x >3:
  31.         x = (x >> 2) + (x & 0x3)
  32.     if (x == 3):
  33.         counter += 1
  34.     # old style
  35.     '''
  36.    num  = number
  37.    summ = 0
  38.    while num:
  39.        num, mod = divmod(num, 10)
  40.        summ += mod
  41.    if summ % 3 == 0:
  42.        counter += 1  
  43.    '''
  44.    
  45. t2 = time.monotonic()    
  46. delta = t2-t1    
  47. print('%.6fs' % delta, counter)
  48.  
  49. # input N: 1000
  50. # 1.653000s 666
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement