Skip to content

Instantly share code, notes, and snippets.

@ffoxin
Created January 21, 2014 10:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ffoxin/8537513 to your computer and use it in GitHub Desktop.
Save ffoxin/8537513 to your computer and use it in GitHub Desktop.
Möbius function visualization using mathplotlib
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Vital Kolas'
__version__ = '0.0.1'
from pylab import *
from collections import Counter
if __name__ == '__main__':
max_value = 30
primaries = Counter()
numbers = range(1, max_value)
mob = []
for value in numbers:
# check if square-free
if value == 1:
mob.append(1)
else:
is_square_free = True
for primary in primaries:
perfect_square = primary ** 2
if value >= perfect_square and value % perfect_square == 0:
is_square_free = False
break
# count prime factors
factor_count = 1
for primary in primaries:
if value % primary == 0:
factor_count = primaries[primary] + primaries[value // primary]
break
# calc Möbius function
if is_square_free:
mob_value = -1 if factor_count % 2 else 1
else:
mob_value = 0
primaries[value] = factor_count
mob.append(mob_value)
plot(numbers, mob, marker = 'o', linestyle = '')
ylim([-2, 2])
grid(True)
show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment