Skip to content

Update maths/cube_number.py #31

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 8, 2021
Merged

Update maths/cube_number.py #31

merged 1 commit into from
Jan 8, 2021

Conversation

taseikyo
Copy link
Contributor

Skip the invalid loops

In [1]: def is_cube_number(number: int) -> bool:
   ...:     number = abs(number)
   ...:     for i in range(0, number + 1):
   ...:         if i ** 3 == number:
   ...:             return True
   ...:     return False
   ...:

In [2]: def is_cube_number_fast(number: int) -> bool:
   ...:     number = abs(number)
   ...:     for i in range(0, number + 1):
   ...:         if i ** 3 == number:
   ...:             return True
   ...:         if i ** 3 > number:
   ...:             return False
   ...:     return False
   ...:

In [3]: %timeit -n10 is_cube_number_fast(2**20)
35.7 µs ± 494 ns per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [4]: %timeit -n10 is_cube_number(2**20)
214 ms ± 1.83 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Copy link
Member

@realDuYuanChao realDuYuanChao left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your contribution

@realDuYuanChao realDuYuanChao merged commit d957853 into examplehub:master Jan 8, 2021
@taseikyo taseikyo deleted the patch branch January 8, 2021 10:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants