Advertisement
banovski

Triangular number verifier (Python)

Nov 15th, 2022 (edited)
1,080
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.47 KB | Source Code | 0 0
  1. #! /usr/bin/env python3
  2.  
  3. the_number = 1000000000000
  4.  
  5. def is_triangular_number_formula(number):
  6.     root_of_square = (number * 8 + 1) ** 0.5
  7.     return root_of_square == round(root_of_square)
  8.  
  9. # print(is_triangular_number_formula(the_number))
  10. # 6 function calls in 0.000 seconds
  11.  
  12. def is_triangular_number_algorithm_one(number):
  13.     accumulator = 0
  14.     counter = 0
  15.    
  16.     while accumulator <= number:
  17.         accumulator += counter
  18.         counter += 1
  19.  
  20.         if accumulator == number:
  21.             result = True
  22.             break
  23.     else:
  24.         result = False
  25.  
  26.     return result
  27.  
  28. # print(is_triangular_number_algorithm_one(the_number))
  29. # 5 function calls in 0.474 seconds
  30.  
  31. def is_triangular_number_algorithm_two(number):
  32.     counter = 0
  33.  
  34.     if number == 0:
  35.         return True
  36.    
  37.     while number > 0:
  38.         counter += 1
  39.         number -= counter
  40.  
  41.         if number == 0:
  42.             result = True
  43.             break
  44.     else:
  45.         result = False
  46.  
  47.     return result
  48.  
  49. # print(is_triangular_number_algorithm_two(the_number))
  50. # 5 function calls in 0.419 seconds
  51.  
  52. def is_triangular_number_algorithm_three(number):
  53.     for counter in range(number + 1):
  54.         triangular_number = counter * (counter + 1) // 2
  55.         if number == triangular_number:
  56.             return True
  57.         if number < triangular_number:
  58.             return False
  59.  
  60. # print(is_triangular_number_algorithm_three(the_number))
  61. # 5 function calls in 0.679 seconds
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement