Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.forth > #50499 > unrolled thread

Rosetta Code: Happy numbers

Started by"WJ" <w_a_x_man@yahoo.com>
First post2016-08-26 22:05 +0000
Last post2016-08-26 18:07 -0700
Articles 2 — 2 participants

Back to article view | Back to comp.lang.forth


Contents

  Rosetta Code: Happy numbers "WJ" <w_a_x_man@yahoo.com> - 2016-08-26 22:05 +0000
    Re: Rosetta Code: Happy numbers Paul Rubin <no.email@nospam.invalid> - 2016-08-26 18:07 -0700

#50499 — Rosetta Code: Happy numbers

From"WJ" <w_a_x_man@yahoo.com>
Date2016-08-26 22:05 +0000
SubjectRosetta Code: Happy numbers
Message-ID<npqefl$l8o$1@dont-email.me>
> Starting with any positive integer, replace the number by the
> sum of the squares of its digits, and repeat the process until
> the number equals 1 (where it will stay), or it loops
> endlessly in a cycle which does not include 1.   Those
> numbers for which this process ends in 1 are happy
> numbers, while those that do not end in 1 are unhappy
> numbers.
> 
> task
> 
> Find and print the first 8 happy numbers.

Ruby:

def sum_sq_digits n
  0==n ? 0 : (q,r = n.divmod 10; r*r + sum_sq_digits(q))
end

$memory = Hash.new

def happy? n, seq=[]
  result =
    if $memory.include?(n)
      $memory[n]
    elsif 1==n
      true
    elsif seq.include? n
      false
    end
  if nil != result
    seq.select{|m| m<999}.each{|m| $memory[m]=result}
    return result
  end
  happy?(sum_sq_digits(n), seq<<n)
end

happy = Enumerator.new{|y|
  n = 1
  loop{y.yield(n) if happy?(n); n+=1}
}

happy.take(15)
    ==>[1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82]

## 1_000_000th happy number
happy.with_index.find{|n,i| 999_999==i}.first
 ===>
7105849

In Forth?

-- 
In Denmark and Norway, between 65% and 70% of all rapes are committed by
Muslims....  One local judge in Norway actually exonerated one rapist by
accepting his defense that the victim's dress was taken by him to mean that she
was egging him on.
http://fjordman.blogspot.com/2005/08/rape-nothing-to-do-with-islam.html

[toc] | [next] | [standalone]


#50501

FromPaul Rubin <no.email@nospam.invalid>
Date2016-08-26 18:07 -0700
Message-ID<87y43jow83.fsf@jester.gateway.pace.com>
In reply to#50499
"WJ" <w_a_x_man@yahoo.com> writes:
> $memory = Hash.new
> def happy? n, seq=[]
>   result =
>     if $memory.include?(n)
>      ... many more lines of crap bloaty code

Bleccch, how tasteless.

: ssd ( n -- n ) 0 swap			  \ sum of squares of digits
    begin dup while 10 /mod swap dup * rot + swap repeat drop ;
: happy ( n -- flag ) dup begin ssd swap ssd ssd swap 2dup = until drop 1 = ;
: go ( n -- ) 0 swap 0 do begin 1+ dup happy until dup . loop ;

15 go =>
15 go 1 7 10 13 19 23 28 31 32 44 49 68 70 79 82  ok

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.forth


csiph-web