减少基本图形公式的复杂度/计算时间 [英] Reducing the complexity/computation time for a basic graph formula

查看:75
本文介绍了减少基本图形公式的复杂度/计算时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用基本公式(是从另一个SO问题中得到的),用于计算 n 个顶点的不同边集的最大数量:

I tried to use the basic formula (got it from another SO question), for calculating the max number of different edge sets, for n vertices:

2**(n*(n-1)/2)

但是它仅对小范围的数字有用-然后变得太复杂了.

but it's good only for small range of numbers - then it gets too complex.

有没有办法改善这个公式/降低复杂性?

Is there a way to improve this formula/reduce the complexity?

推荐答案

这是一种大大加快此速度的简便方法: 2 ** x 始终等于 1<<x ,只要 x 是非负整数;但后者要快上百倍,因为它只是移位位,而不是进行算术运算

Here's an easy way to speed this up quite considerably: 2 ** x is always equal to 1 << x, so long as x is a non-negative integer; but the latter is hundreds of times faster, because it's just shifting bits rather than doing arithmetic.

>>> def slow(n):
...     return 2 ** (n * (n-1) // 2)
... 
>>> def fast(n):
...     return 1 << (n * (n-1) // 2)
... 
>>> from timeit import timeit
>>> timeit(lambda: slow(1000), number=1000)
1.5656050549987413
>>> timeit(lambda: fast(1000), number=1000)
0.005352460000722203

这篇关于减少基本图形公式的复杂度/计算时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆