Compute all combinations of where a and b are integers between 2 and 5 inclusive.
Place them in numerical order, with any repeats removed.
You should get the following sequence of 15 distinct terms:
4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125
print(sorted(Array(Set(cart_product(2..5, 2..5).map((a, b) -> a ^ b)))))
[4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125]
INCLUDE "D2:SORT.ACT" ;from the Action! Tool KitINT FUNC Power(INT a,b) INT res,i res=1 FOR i=1 TO b DO res==*a ODRETURN (res)BYTE FUNC Contains(INT ARRAY a INT count,x) INT i FOR i=0 TO count-1 DO IF a(i)=x THEN RETURN (1) FI ODRETURN (0)PROC Main() INT ARRAY a(100) INT i,j,x,count Put(125) PutE() ;clear the screen count=0 FOR i=2 TO 5 DO FOR j=2 TO 5 DO x=Power(i,j) IF Contains(a,count,x)=0 THEN a(count)=x count==+1 FI OD OD SortI(a,count,0) FOR i=0 TO count-1 DO PrintI(a(i)) Put(32) ODRETURN
Screenshot from Atari 8-bit computer
4 8 9 16 25 27 32 64 81 125 243 256 625 1024 3125
withAda.Text_Io;withAda.Containers.Doubly_Linked_Lists;procedurePower_NumbersispackageNumber_Listsis newAda.Containers.Doubly_Linked_Lists(Integer);packageNumber_Sortingis newNumber_Lists.Generic_Sorting;useNumber_Lists,Ada.Text_Io;List:Number_Lists.List;beginforAin2..5loopforBin2..5loopdeclareR:constantInteger:=A**B;beginifnotList.Contains(R)thenList.Append(R);endif;end;endloop;endloop;Number_Sorting.Sort(List);forEofListloopPut(Integer'Image(E));Put(" ");endloop;New_Line;endPower_Numbers;
4 8 9 16 25 27 32 64 81 125 243 256 625 1024 3125
BEGIN # show in order, distinct values of a^b where 2 <= a <= b <= 5 # INT max number = 5; INT min number = 2; # construct a table of a ^ b # INT length = ( max number + 1 ) - min number; [ 1 : length * length ]INT a to b; INT pos := 0; FOR i FROM min number TO max number DO a to b[ pos +:= 1 ] := i * i; FROM min number + 1 TO max number DO INT prev = pos; a to b[ pos +:= 1 ] := a to b[ prev ] * i OD OD; # sort the table # # it is small and nearly sorted so a bubble sort should suffice # FOR u FROM UPB a to b - 1 BY -1 TO LWB a to b WHILE BOOL sorted := TRUE; FOR p FROM LWB a to b BY 1 TO u DO IF a to b[ p ] > a to b[ p + 1 ] THEN INT t = a to b[ p ]; a to b[ p ] := a to b[ p + 1 ]; a to b[ p + 1 ] := t; sorted := FALSE FI OD; NOT sorted DO SKIP OD; # print the table, excluding duplicates # INT last := -1; FOR i TO UPB a to b DO INT next = a to b[ i ]; IF next /= last THEN print( ( " ", whole( next, 0 ) ) ) FI; last := next OD; print( ( newline ) )END
4 8 9 16 25 27 32 64 81 125 243 256 625 1024 3125
(⊂∘⍋⌷⊣)∪,∘.*⍨1+⍳4
4 8 9 16 25 27 32 64 81 125 243 256 625 1024 3125
Uses an extravagantly long list, but gets the job done quickly and easily.
ontask()scriptopropertyoutput:{}endscriptrepeat(5^5)timessetendofo'soutputtomissing valueendrepeatrepeatwithafrom2to5repeatwithbfrom2to5tell(a^basinteger)tosetitemitofo'soutputtoittell(b^aasinteger)tosetitemitofo'soutputtoitendrepeatendrepeatreturno'soutput'sintegersendtasktask()
{4,8,9,16,25,27,32,64,81,125,243,256,625,1024,3125}
Composing a solution from generic primitives, for speed of drafting, and ease of refactoring:
useframework"Foundation"usescriptingadditions------------------ DISTINCT POWER VALUES ------------------- distinctPowers :: [Int] -> [Int]ondistinctPowers(xs)scriptpowerson|λ|(a,x)scriptintegerPoweron|λ|(b,y)b'saddObject:((x^y)asinteger)bend|λ|endscriptfoldl(integerPower,a,xs)end|λ|endscriptsort(foldl(powers,¬current application'sNSMutableSet'salloc'sinit(),xs)'s¬allObjects())enddistinctPowers--------------------------- TEST -------------------------onrundistinctPowers(enumFromTo(2,5))endrun------------------------- GENERIC -------------------------- enumFromTo :: Int -> Int -> [Int]onenumFromTo(m,n)ifm≤nthensetlstto{}repeatwithifrommtonsetendoflsttoiendrepeatlstelse{}endifendenumFromTo-- foldl :: (a -> b -> a) -> a -> [b] -> aonfoldl(f,startValue,xs)tellmReturn(f)setvtostartValuesetlngtolengthofxsrepeatwithifrom1tolngsetvto|λ|(v,itemiofxs,i,xs)endrepeatreturnvendtellendfoldl-- mReturn :: First-class m => (a -> b) -> m (a -> b)onmReturn(f)-- 2nd class handler function lifted into 1st class script wrapper.ifscriptisclassoffthenfelsescriptproperty|λ|:fendscriptendifendmReturn-- sort :: Ord a => [a] -> [a]onsort(xs)((current application'sNSArray'sarrayWithArray:xs)'s¬sortedArrayUsingSelector:"compare:")aslistendsort
{4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125}
Throwing together a solution using the most appropriate methods for efficiency and legibility.
useAppleScriptversion"2.4"-- Mac OS X 10.10 (Yosemite) or later.useframework"Foundation"ontask()setnumsto{}repeatwithafrom2to5repeatwithbfrom2to5setendofnumsto(a^b)asintegersetendofnumsto(b^a)asintegerendrepeatendrepeatsetnumstocurrent application'sclass"NSSet"'ssetWithArray:(nums)setdescriptortocurrent application'sclass"NSSortDescriptor"'ssortDescriptorWithKey:("self")ascending:(true)return(nums'ssortedArrayUsingDescriptors:({descriptor}))aslistendtasktask()
{4,8,9,16,25,27,32,64,81,125,243,256,625,1024,3125}
printsortuniqueflattenmap2..5'a[map2..5'b-> a^b]
4 8 9 16 25 27 32 64 81 125 243 256 625 1024 3125
get "libhdr"let pow(n, p) = p=0 -> 1, n * pow(n, p-1)let sort(v, length) be if length > 0 $( for i=0 to length-2 if v!i > v!(i+1) $( let t = v!i v!i := v!(i+1) v!(i+1) := t $) sort(v, length-1) $)let start() be $( let v = vec 15 let i = 0 for a = 2 to 5 for b = 2 to 5 $( v!i := pow(a,b) i := i+1 $) sort(v, 16) for i = 0 to 15 if i=0 | v!i ~= v!(i-1) do writef("%N ", v!i) wrch('*N')$)
4 8 9 16 25 27 32 64 81 125 243 256 625 1024 3125
∧⍷⥊⋆⌜˜2+↕4
⟨ 4 8 9 16 25 27 32 64 81 125 243 256 625 1024 3125 ⟩
#include<stdio.h>#include<stdlib.h>#include<math.h>intcompare(constvoid*a,constvoid*b){intia=*(int*)a;intib=*(int*)b;return(ia>ib)-(ia<ib);}intmain(){intpows[16];inta,b,i=0;for(a=2;a<=5;a++)for(b=2;b<=5;b++)pows[i++]=pow(a,b);qsort(pows,16,sizeof(int),compare);for(i=0;i<16;i++)if(i==0||pows[i]!=pows[i-1])printf("%d ",pows[i]);printf("\n");return0;}
4 8 9 16 25 27 32 64 81 125 243 256 625 1024 3125
#include<iostream>#include<set>#include<cmath>intmain(){std::set<int>values;for(inta=2;a<=5;a++)for(intb=2;b<=5;b++)values.insert(std::pow(a,b));for(inti:values)std::cout<<i<<" ";std::cout<<std::endl;return0;}
4 8 9 16 25 27 32 64 81 125 243 256 625 1024 3125
set[fornin2..5doforgin2..5->pownng]|>Set.iter(printf"%d ")
4 8 9 16 25 27 32 64 81 125 243 256 625 1024 3125
Uses Delphi's standard StringList control to avoid duplicates and keep the list storted. It uses a trick to make the strings sorted numerically. The number strings are stored with leading zeros to make them sort numericall and the actual number is stored as an object so it can be retrieved without the leading zeros.
procedureFindDistinctPowers(Memo:TMemo);{Display list of numbers a^b sort and exclude duplicates}{tricks Delphi TStringGrid into sorting numerically}varA,B,I,P:integer;varSL:TStringList;beginSL:=TStringList.Create;trySL.Duplicates:=dupIgnore;SL.Sorted:=True;forA:=2to5doforB:=2to5dobeginP:=Trunc(Power(A,B));{Add leading zeros to number so it sorts numerically}SL.AddObject(FormatFloat('00000',P),Pointer(P));end;Memo.Text:=IntToStr(integer(SL.Objects[0]));forI:=1toSL.Count-1doMemo.Text:=Memo.Text+','+IntToStr(integer(SL.Objects[I]));finallySL.Free;end;end;
4,8,9,16,25,27,32,64,81,125,243,256,625,1024,3125
selectDISTINCTpower(a,b)::INTEGERas"a^b"fromrange(2,6)t(a),range(2,6)asu(b)orderby"a^b";
┌───────┐│ a^b ││ int32 │├───────┤│ 4 ││ 8 ││ 9 ││ 16 ││ 25 ││ 27 ││ 32 ││ 64 ││ 81 ││ 125 ││ 243 ││ 256 ││ 625 ││ 1024 ││ 3125 │└───────┘
To convert to a DuckDB list, one could use array_agg().
USING:kernelmath.functionsmath.rangesprettyprintsequencessetssorting;2 5[a,b]dup[^]cartesian-mapconcatmembersnatural-sort.
{ 4 8 9 16 25 27 32 64 81 125 243 256 625 1024 3125 }
redimarr(-1)asuintegerdimasuintegeriforaasuinteger=2to5forbasuinteger=2to5redimpreservearr(0toubound(arr)+1)i=ubound(arr)arr(i)=a^bwhilearr(i-1)>arr(i)andi>0swaparr(i-1),arr(i)i-=1wendnextbnextafori=0toubound(arr)ifarr(i)<>arr(i-1)thenprintarr(i),nexti
packagemainimport("fmt""rcu""sort")funcmain(){varpows[]intfora:=2;a<=5;a++{pow:=aforb:=2;b<=5;b++{pow*=apows=append(pows,pow)}}set:=make(map[int]bool)for_,e:=rangepows{set[e]=true}pows=pows[:0]fork:=rangeset{pows=append(pows,k)}sort.Ints(pows)fmt.Println("Ordered distinct values of a ^ b for a in [2..5] and b in [2..5]:")fori,pow:=rangepows{fmt.Printf("%5s ",rcu.Commatize(pow))if(i+1)%5==0{fmt.Println()}}fmt.Println("\nFound",len(pows),"such numbers.")}
Ordered distinct values of a ^ b for a in [2..5] and b in [2..5]: 4 8 9 16 25 27 32 64 81 125 243 256 625 1,024 3,125 Found 15 such numbers.
importqualifiedData.SetasS------------------ DISTINCT POWER NUMBERS ----------------distinctPowerNumbers::Int->Int->[Int]distinctPowerNumbersab=(S.elems.S.fromList)$(fmap(^)>>=(<*>))[a..b]--------------------------- TEST -------------------------main::IO()main=print$distinctPowerNumbers25
[4,8,9,16,25,27,32,64,81,125,243,256,625,1024,3125]
or, as a one-off list comprehension:
importqualifiedData.SetasSmain::IO()main=(print.S.elems.S.fromList)$(\xs->[x^y|x<-xs,y<-xs])[2..5]
or a liftA2 expression:
importControl.Applicative(liftA2)importControl.Monad(join)importqualifiedData.SetasSmain::IO()main=(print.S.elems.S.fromList)$join(liftA2(^))[2..5]
which can always be reduced (shedding imports) to the pattern:
importqualifiedData.SetasSmain::IO()main=(print.S.elems.S.fromList)$(\xs->(^)<$>xs<*>xs)[2..5]
[4,8,9,16,25,27,32,64,81,125,243,256,625,1024,3125]
~./:~;^/~2+i.4
4 8 9 16 25 27 32 64 81 125 243 256 625 1024 3125
importjava.util.Set;importjava.util.TreeSet;publicfinalclassDistinctPowerNumbers{publicstaticvoidmain(String[]args){Set<Integer>values=newTreeSet<Integer>();for(inta=2;a<=5;a++){for(intb=2;b<=5;b++){values.add((int)Math.pow(a,b));}}System.out.println(values);}}
[4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125]
Works with gojq, the Go implementation of jq
For relatively small integers, such as involved in the specified task, the built-in function `pow/2` does the job:
[range(2;6) as $a | range(2;6) as $b | pow($a; $b)] | unique
[4,8,9,16,25,27,32,64,81,125,243,256,625,1024,3125]
However, if using gojq, then for unbounded precision, a special-purpose "power" function is needed:
def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);[range(2;6) as $a | range(2;6) as $b | $a|power($b)] | unique
As above.
println(sort(unique([a^bforain2:5,bin2:5])))
[4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125]
Union@@Table[a^b,{a,2,5},{b,2,5}]
{4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125}
importalgorithm,math,sequtils,strutils,sugarletlist=collect(newSeq):forain2..5:forbin2..5:a^bechosorted(list).deduplicate(true).join(" ")
4 8 9 16 25 27 32 64 81 125 243 256 625 1024 3125
moduleIntSet=Set.Make(Int)letpowx=letrecauxaccb=function|0->acc|y->aux(ifyland1=0thenaccelseacc*b)(b*b)(ylsr1)inaux1xletdistinct_powersfirstcount=letsq=Seq.(takecount(intsfirst))inIntSet.of_seq(Seq.map_productpowsqsq)let()=distinct_powers24(* output *)|>IntSet.to_seq|>Seq.mapstring_of_int|>List.of_seq|>String.concat" "|>print_endline
4 8 9 16 25 27 32 64 81 125 243 256 625 1024 3125
withjavascript_semanticsfunctionsqpn(integern)returnsq_power(n,{2,3,4,5})endfunctionsequenceres=apply(true,sprintf,{{"%,5d"},unique(join(apply({2,3,4,5},sqpn),""))})printf(1,"%d found:\n%s\n",{length(res),join_by(res,1,5," ")})
15 found: 4 8 9 16 25 27 32 64 81 125 243 256 625 1,024 3,125
#!/usr/bin/perl -lusestrict;# https://rosettacode.org/wiki/Distinct_power_numbersusewarnings;useList::Utilqw( uniq );printjoin', ',sort{$a<=>$b}uniqmap{my$e=$_;map$_**$e,2..5}2..5;
4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125
fromitertoolsimportproductprint(sorted(set(a**bfor(a,b)inproduct(range(2,6),range(2,6)))))
[4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125]
Or, for variation, generalizing a little in terms ofstarmap andpow:
'''Distinct power numbers'''fromitertoolsimportproduct,starmap# distinctPowerNumbers :: Int -> Int -> [Int]defdistinctPowerNumbers(a):'''Sorted values of x^y where x, y <- [a..b] '''defgo(b):xs=range(a,1+b)returnsorted(set(starmap(pow,product(xs,xs))))returngo# ------------------------- TEST -------------------------# main :: IO ()defmain():'''Distinct powers from integers [2..5]'''print(distinctPowerNumbers(2)(5))# MAIN ---if__name__=='__main__':main()
[4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125]
This only takes one line.
unique(sort(rep(2:5,each=4)^rep(2:5,times=4)))
[1] 4 8 9 16 25 27 32 64 81 125 243 256 625 1024 3125
[ [] swap behead swap witheach [ 2dup = iff drop done dip join ] join ] is unique ( [ --> [ ) [] 4 times [ i 2 + 4 times [ dup i 2 + ** rot join swap ] drop ] sort unique echo
[ 4 8 9 16 25 27 32 64 81 125 243 256 625 1024 3125 ]
putsquishsort [X**] (2..5)xx2;
4 8 9 16 25 27 32 64 81 125 243 256 625 1024 3125
With this version of REXX, there's no need to sort the found numbers, or to eliminate duplicates.
/*REXX pgm finds and displays distinct power integers: a^b, where a and b are 2≤both≤5*/parsearglohicols./*obtain optional arguments from the CL*/iflo==''|lo==","thenlo=2/*Not specified? Then use the default.*/ifhi==''|hi==","thenhi=5/* " " " " " " */ifcols==''|cols==","thencols=10/* " " " " " " */w=11/*width of a number in any column. */title=' distinct power integers, a^b, where a and b are: 'lo"≤ both ≤"hisay' index │'center(title,1+cols*(w+1))say'───────┼'center("",1+cols*(w+1),'─')@.=.;$$=/*the default value for the @. array.*/doa=lotohi/*traipse through A values (LO──►HI).*/dob=lotohi/* " " B " " " */x=a**b;if@.x\==.theniterate/*Has it been found before? Then skip.*/@.x=x;$$=$$x/*assign power product; append to $$ */end/*b*/end/*a*/$=;idx=1/*$$: a list of distinct power integers*/doj=1whilewords($$)>0;callgetMin$$/*obtain smallest number in the $$ list*/$=$right(commas(z),max(w,length(z)))/*add a distinct power number ──► list.*/ifj//cols\==0theniterate/*have we populated a line of output? */saycenter(idx,7)'│'substr($,2);$=/*display what we have so far (cols). */idx=idx+cols/*bump the index count for the output*/end/*j*/if$\==''thensaycenter(idx,7)"│"substr($,2)/*possible display residual output.*/say'───────┴'center("",1+cols*(w+1),'─')saysay'Found 'commas(j-1)titleexit0/*stick a fork in it, we're all done. *//*──────────────────────────────────────────────────────────────────────────────────────*/commas:parsearg?;dojc=length(?)-3to1by-3;?=insert(',',?,jc);end;return?/*──────────────────────────────────────────────────────────────────────────────────────*/getMin:parseargz.;p=1;#=words($$)/*assume min; # words in $$.*/dom=2for#-1;a=word($$,m);ifa>=ztheniterate;z=a;p=mend/*m*/;$$=delword($$,p,1);return/*delete the smallest number.*/
index │ distinct power integers, a^b, where a and b are: 2 ≤ both ≤ 5───────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── 1 │ 4 8 9 16 25 27 32 64 81 125 11 │ 243 256 625 1,024 3,125───────┴─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────Found 15 distinct power integers, a^b, where a and b are: 2 ≤ both ≤ 5
index │ distinct power integers, a^b, where a and b are: 0 ≤ both ≤ 5───────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── 1 │ 0 1 2 3 4 5 8 9 16 25 11 │ 27 32 64 81 125 243 256 625 1,024 3,125───────┴─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
index │ distinct power integers, a^b, where a and b are: 0 ≤ both ≤ 9───────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── 1 │ 0 1 2 3 4 5 6 7 8 9 11 │ 16 25 27 32 36 49 64 81 125 128 21 │ 216 243 256 343 512 625 729 1,024 1,296 2,187 31 │ 2,401 3,125 4,096 6,561 7,776 15,625 16,384 16,807 19,683 32,768 41 │ 46,656 59,049 65,536 78,125 117,649 262,144 279,936 390,625 531,441 823,543 51 │ 1,679,616 1,953,125 2,097,152 4,782,969 5,764,801 10,077,696 16,777,216 40,353,607 43,046,721 134,217,728 61 │ 387,420,489───────┴─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────Found 61 distinct power integers, a^b, where a and b are: 0 ≤ both ≤ 9
load "stdlib.ring"see "working..." + nlsee "Distinct powers are:" + nlrow = 0distPow = []for n = 2 to 5 for m = 2 to 5 sum = pow(n,m) add(distPow,sum) nextnextdistPow = sort(distPow)for n = len(distPow) to 2 step -1 if distPow[n] = distPow[n-1] del(distPow,n-1) oknextfor n = 1 to len(distPow) row++ see "" + distPow[n] + " " if row%5 = 0 see nl oknext see "Found " + row + " numbers" + nlsee "done..." + nl
working...Distinct powers are:4 8 9 16 25 27 32 64 81 125 243 256 625 1024 3125 Found 15 numbersdone...
≪ { } 2 5FOR a 2 5FOR b a b ^IF DUP2 POSTHEN DROPELSE +ENDNEXT NEXT SORT≫ 'DPOWR' STO
1: { 4 8 9 16 25 27 32 64 81 125 243 256 625 1024 3125 }
a=(2..5).to_apa.product(a).map{_1**_2}.sort.uniq
[4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125]
useitertools::Itertools;fnmain(){letmutv=[2_u32,3,4,5].into_iter().map(|a|[2_u32,3,4,5].iter().map(|b|a.pow(*b)).collect_vec()).concat();v.sort();v.dedup();println!("{:?}",v);}
[4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125]
[2..5]*2->cartesian.map_2d{|a,b|a**b}.sort.uniq.say
Alternative solution:
2..5~X**2..5->sort.uniq.say
[4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125]
import"./seq"forLstimport"./fmt"forFmtvarpows=[]for(ain2..5){varpow=afor(bin2..5){pow=pow*apows.add(pow)}}pows=Lst.distinct(pows).sort()System.print("Ordered distinct values of a ^ b for a in [2..5] and b in [2..5]:")Fmt.tprint("$,5d",pows,5)System.print("\nFound%(pows.count) such numbers.")
Ordered distinct values of a ^ b for a in [2..5] and b in [2..5]: 4 8 9 16 25 27 32 64 81 125 243 256 625 1,024 3,125Found 15 such numbers.
int A, B, N, Last, Next;[Last:= 0;loop [Next:= -1>>1; \infinity for A:= 2 to 5 do \find smallest Next for B:= 2 to 5 do \ that's > Last [N:= fix(Pow(float(A), float(B))); if N>Last & N<Next then Next:= N; ]; if Next = -1>>1 then quit; IntOut(0, Next); ChOut(0, ^ ); Last:= Next; ];]
4 8 9 16 25 27 32 64 81 125 243 256 625 1024 3125