Jump to content

Magnanimous numbers: Difference between revisions

→‎{{header|Factor}}: replace with simpler, faster version
(→‎{{header|Factor}}: replace with simpler, faster version)
Line 177:
</pre>
=={{header|Factor}}==
{{trans|Julia}}
{{works with|Factor|0.99 2020-01-23}}
<lang factor>USING: arrays grouping io kernel lists lists.lazy math math.functions
lists.lazy.examples math math.parser math.primes math.ranges prettyprint sequences ;
prettyprint sequences ;
 
: magnanimous? ( strn -- ? )
! Optimization for numbers > 1001;
dup length10 1 =< [ drop t ] [ (magnanimous?) ] if ;
! first and last digits must have opposite parity.
dup log10 >integer [1,b] [
! Thanks to Raku entry for this.
10^ /mod + prime? not
: mixed-parity? ( str -- ? )
[ first even? ] [with lastfind even? xor ]nip bi>boolean ;not
] if ;
 
: (magnanimous?) ( strn -- ?seq )
: >stringy ( l -- l ) [ number>string ] lmap-lazy ;
: 1001- ( -- l0 ) naturalslfrom [ 1002magnanimous? <] ]lfilter lwhileltake list>stringyarray ;
: 1002+ ( -- l ) 1002 lfrom >stringy [ mixed-parity? ] lfilter ;
: candidates ( -- l ) 1001- 1002+ lappend-lazy ;
 
: (magnanimous?) ( str -- ? )
dup length 1 - [1,b] [ cut 2array ] with map
[ [ string>number ] map-sum ] map [ prime? ] all? ;
 
: magnanimous? ( str -- ? )
dup length 1 = [ drop t ] [ (magnanimous?) ] if ;
 
: magnanimous ( -- l ) candidates [ magnanimous? ] lfilter ;
 
: show ( seq from to -- ) rot subseq 15 group simple-table. nl ;
 
400 magnanimous ltake list>array
[ "First 45 magnanimous numbers" print 0 45 show ]
[ "241st through 250th magnanimous numbers" print 240 250 show ]
1,827

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.