From: Sebastian Hungerecker Date: 2008-09-26T17:48:26+09:00 Subject: Re: [SUMMARY] One-Liners Mashup (#177) Matthew Moss wrote: > The problem: > > Write a function per(n) which returns the periodicity of 1/n, i.e. > per(3) => 1 > per(4) => 0 > per(7) => 6 > per(11) => 2 > > The "Ummm... yeah... how do these work?" solution: > > def per(n, b=10) > i=1;x=b;h={};loop {x=x%n*b;break 0 if x==0;h[x]?(break > i-h[x]):h[x]=i; i+=1} > end It works like this: http://img243.imageshack.us/img243/9296/perwt4.png It simply divides until the remainder repeats itself (storing the position where each remainder occured in a hash) and then returns the difference between the first position where the remainder occured (i.e. the start of the period) and the current position. -- Jabber: sepp2k@jabber.org ICQ: 205544826