Colorful numbers: Difference between revisions

Added Easylang
(Added Java solution)
(Added Easylang)
 
(38 intermediate revisions by 17 users not shown)
Line 1:
{{draft task}}
 
A '''colorful number''' is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique.
Line 33:
 
''Colorful numbers have no real number theory application. They are more a recreational math puzzle than a useful tool.''
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">V largest = [0]
 
F iscolorful(n)
I n C 0.<10
R 1B
V dig = String(n).map(c -> Int(c))
I 1 C dig | 0 C dig | dig.len > Set(dig).len
R 0B
V products = Array(Set(dig))
L(i) 0 .< dig.len
L(j) i + 2 .. dig.len
V p = product(dig[i .< j])
I p C products
R 0B
products.append(p)
 
:largest[0] = max(n, :largest[0])
R 1B
 
print(‘Colorful numbers for 1:25, 26:50, 51:75, and 76:100:’)
L(i) (1.<101).step(25)
L(j) 25
I iscolorful(i + j)
print(f:‘{commatize(i + j): 5}’, end' ‘’)
print()
 
V csum = 0
L(i) 8
V j = I i == 0 {0} E 10 ^ i
V k = 10 ^ (i + 1) - 1
V n = sum((j .. k).map(x -> Int(iscolorful(x))))
csum += n
print(‘The count of colorful numbers between ’j‘ and ’k‘ is ’n‘.’)
 
print(‘The largest possible colorful number is ’largest[0]‘.’)
print(‘The total number of colorful numbers is ’csum‘.’)</syntaxhighlight>
 
{{out}}
<pre>
Colorful numbers for 1:25, 26:50, 51:75, and 76:100:
1 2 3 4 5 6 7 8 9 23 24 25
26 27 28 29 32 34 35 36 37 38 39 42 43 45 46 47 48 49
52 53 54 56 57 58 59 62 63 64 65 67 68 69 72 73 74 75
76 78 79 82 83 84 85 86 87 89 92 93 94 95 96 97 98
The count of colorful numbers between 0 and 9 is 10.
The count of colorful numbers between 10 and 99 is 56.
The count of colorful numbers between 100 and 999 is 328.
The count of colorful numbers between 1000 and 9999 is 1540.
The count of colorful numbers between 10000 and 99999 is 5514.
The count of colorful numbers between 100000 and 999999 is 13956.
The count of colorful numbers between 1000000 and 9999999 is 21596.
The count of colorful numbers between 10000000 and 99999999 is 14256.
The largest possible colorful number is 98746253.
The total number of colorful numbers is 57256.
</pre>
 
=={{header|ALGOL 68}}==
Using brute force for the stretch.
<syntaxhighlight lang="algol68">
BEGIN # find colourful numbers: numbers where the product of every sub-group #
# of digits is uniue ( non-negative numbers only ) #
# note that (as stated in the task) for multi-digit numbers, the #
# digits 0 and 1 cannot appear #
 
# returns TRUE if n is colourful, FALSE otherswise #
PROC is colourful = ( INT n )BOOL:
IF n < 0 THEN FALSE
ELIF n < 10 THEN TRUE
ELSE
# more than 1 digit - must teat the digits and digit groups #
INT v := n;
# table to hold the digits and groups, as 0 and 1 can't #
# appear, there will be at most 8 digits so at most 36 groups #
[ 1 : 46 ]INT dg;
# split and count the digits #
[ 0 : 9 ]INT d count;
INT s end := 0; # position of the last single digit in dg #
FOR i FROM LWB d count TO UPB d count DO d count[ i ] := 0 OD;
BOOL unique := TRUE;
WHILE v > 0 AND unique DO
INT d = v MOD 10;
dg[ s end +:= 1 ] := d;
unique := 1 = ( d count[ d ] +:= 1 );
v OVERAB 10
OD;
IF unique THEN unique := d count[ 0 ] + d count[ 1 ] = 0 FI;
# form the group products, stopping if one is non-unique #
INT dg pos := s end;
FOR group width FROM 2 TO s end WHILE unique DO
FOR group start TO ( s end + 1 ) - group width WHILE unique DO
INT product := 1;
INT g pos := group start - 1;
FOR i TO group width DO product *:= dg[ g pos +:= 1 ] OD;
dg[ dg pos +:= 1 ] := product;
FOR i TO dg pos - 1 WHILE unique DO
unique := dg[ i ] /= dg[ dg pos ]
OD
OD
OD;
unique
FI # is colourful # ;
 
# show the colourful numbers under 100 #
print( ( "Colourful numbers less than 100:", newline ) );
INT c count := 0;
FOR i FROM 0 TO 99 DO
IF is colourful( i ) THEN
print( ( whole( i, -3 ) ) );
IF ( c count +:= 1 ) MOD 11 = 0 THEN print( ( newline ) ) FI
FI
OD;
print( ( newline ) );
# find the largest colourful number #
INT max colourful := 0;
FOR i FROM 98765432 BY -1 WHILE max colourful = 0 DO
IF is colourful( i ) THEN
max colourful := i
FI
OD;
print( ( "The largest colourful number is: ", whole( max colourful, 0 ), newline ) );
# show the number of colourful numbers by order of magnitude #
INT p10 := 10;
c count := 0;
INT t count := 0;
FOR i FROM 0 TO max colourful DO
IF i = p10 THEN
print( ( "Colourful numbers below ", whole( p10, -10 ), ": ", whole( c count, 0 ), newline ) );
t count +:= c count;
c count := 0;
p10 *:= 10
FI;
IF is colourful( i ) THEN
c count +:= 1
FI
OD;
print( ( "Colourful numbers below ", whole( p10, -10 ), ": ", whole( c count, 0 ), newline ) );
print( ( "Total number of colourful numbers : ", whole( t count + c count, 0 ), newline ) )
END
</syntaxhighlight>
{{out}}
<pre>
Colourful numbers less than 100:
0 1 2 3 4 5 6 7 8 9 23
24 25 26 27 28 29 32 34 35 36 37
38 39 42 43 45 46 47 48 49 52 53
54 56 57 58 59 62 63 64 65 67 68
69 72 73 74 75 76 78 79 82 83 84
85 86 87 89 92 93 94 95 96 97 98
 
The largest colourful number is: 98746253
Colourful numbers below 10: 10
Colourful numbers below 100: 56
Colourful numbers below 1000: 328
Colourful numbers below 10000: 1540
Colourful numbers below 100000: 5514
Colourful numbers below 1000000: 13956
Colourful numbers below 10000000: 21596
Colourful numbers below 100000000: 14256
Total number of colourful numbers : 57256
</pre>
 
=={{header|AppleScript}}==
<syntaxhighlight lang="applescript">(*
This observes the task requirement that colorful numbers be identified using a test handler,
but uses the information regarding 1s and 0s and some logic to skip obvious non-starters
and save a few minutes' running time. Since multiplication is commutative, every number's
"colorful" status is the same as its reverse's. Working up from 0, the lower number of each
mirrored colorful pair is met first and its reverse derived. If the largest reversed number
obtained so far is actually reached, it's the last colorful number at that magnitude. The
search either end there or jumps to the lowest number worth trying at the next level.
*)
on isColorful(n)
if ((n > 98765432) or (n < 0) or (n mod 1 > 0)) then return false
set products to {n mod 10}
repeat while (n > 9)
set n to n div 10
set digit to n mod 10
if ((digit < 2) or (digit is in products)) then return false
set end of products to digit
end repeat
set nDigits to (count products)
repeat with i from 1 to (nDigits - 1)
set prod to products's item i
repeat with j from (i + 1) to nDigits
set prod to prod * (products's item j)
if (prod is in products) then return false
set end of products to prod
end repeat
end repeat
return true
end isColorful
 
on join(lst, delim)
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to delim
set txt to lst as text
set AppleScript's text item delimiters to astid
return txt
end join
 
on task()
set colorfuls to {}
set counter to 0
set counts to {}
set magnitude to 1 -- 10 ^ (number of digits - 1).
set largestReverse to 9 -- Largest reverse of a single-digit number!
set n to 0
repeat
if (isColorful(n)) then
if (n < 100) then set end of colorfuls to text -3 thru -1 of (" " & n)
set counter to counter + 1
if (n = largestReverse) then
set end of counts to counter
set counter to 0
set magnitude to magnitude * 10
if (magnitude > 98765432) then exit repeat
set n to 2.3456789 * magnitude div 1 - 1
else
set temp to n
set |reverse| to temp mod 10
repeat while (temp > 9)
set temp to temp div 10
set |reverse| to |reverse| * 10 + temp mod 10
end repeat
if (|reverse| > largestReverse) then set largestReverse to |reverse|
end if
end if
if (n mod 10 = 9) then
set n to n + 3
else
set n to n + 1
end if
end repeat
set output to {"The colorful numbers below 100:"}
repeat with i from 1 to 66 by 11
set end of output to join(colorfuls's items i thru (i + 10), "")
end repeat
set end of output to linefeed & "The largest colorful number is " & largestReverse
set counter to counts's beginning
set end of output to linefeed & "The number of them with 1 digit is " & counter
repeat with i from 2 to (count counts)
set end of output to "The number with " & i & " digits is " & (counts's item i)
set counter to counter + (counts's item i)
end repeat
set end of output to "The total number overall is " & counter
return join(output, linefeed)
end task
 
task()</syntaxhighlight>
 
{{output}}
<syntaxhighlight lang="applescript">"The colorful numbers below 100:
0 1 2 3 4 5 6 7 8 9 23
24 25 26 27 28 29 32 34 35 36 37
38 39 42 43 45 46 47 48 49 52 53
54 56 57 58 59 62 63 64 65 67 68
69 72 73 74 75 76 78 79 82 83 84
85 86 87 89 92 93 94 95 96 97 98
 
The largest colorful number is 98746253
 
The number of them with 1 digit is 10
The number with 2 digits is 56
The number with 3 digits is 328
The number with 4 digits is 1540
The number with 5 digits is 5514
The number with 6 digits is 13956
The number with 7 digits is 21596
The number with 8 digits is 14256
The total number overall is 57256"</syntaxhighlight>
 
Or here's an alternative using the same <code>isColorful</code> handler but with a translation of the [[#Phix|Phix]] solution's <code>count_colourful</code> function feeding in the numbers. Multi-digit numbers containing 0, 1, or duplicated digits are studiously not produced, so the execution time is very much shorter. (Just over nine seconds on the test machine as opposed to just over six minutes.) Same output as above.
 
<syntaxhighlight lang="applescript">on isColorful(n)
if ((n > 98765432) or (n < 0) or (n mod 1 > 0)) then return false
set products to {n mod 10}
repeat while (n > 9)
set n to n div 10
set digit to n mod 10
if ((digit < 2) or (digit is in products)) then return false
set end of products to digit
end repeat
set nDigits to (count products)
repeat with i from 1 to (nDigits - 1)
set prod to products's item i
repeat with j from (i + 1) to nDigits
set prod to prod * (products's item j)
if (prod is in products) then return false
set end of products to prod
end repeat
end repeat
return true
end isColorful
 
on join(lst, delim)
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to delim
set txt to lst as text
set AppleScript's text item delimiters to astid
return txt
end join
 
on task()
set colorfuls to {}
repeat with n from 0 to 100
if (isColorful(n)) then set end of colorfuls to (" " & n)'s text -3 thru -1
end repeat
script cc
property used : {false, false, false, false, false, false, false, false, false, false}
property counts : {0, 0, 0, 0, 0, 0, 0, 0}
property largest : 0
on count_colourful(taken, x, n)
set used's item x to true
if (isColorful(n)) then
set ln to 1
repeat until ((10 ^ ln) > n)
set ln to ln + 1
end repeat
set counts's item ln to (counts's item ln) + 1
if (n > largest) then set largest to n
end if
if (taken < 9) then
repeat with digit from 2 to 9
set dx to digit + 1
if (not used's item dx) then
count_colourful(taken + 1, dx, n * 10 + digit)
end if
end repeat
end if
set used's item x to false
end count_colourful
end script
repeat with digit from 0 to 9
cc's count_colourful(((digit < 2) as integer) * 8 + 1, digit + 1, digit)
end repeat
set output to {"The colorful numbers below 100:"}
repeat with i from 1 to 66 by 11
set end of output to join(colorfuls's items i thru (i + 10), "")
end repeat
set end of output to linefeed & "The largest colorful number is " & cc's largest
set counter to cc's counts's beginning
set end of output to linefeed & "The number of them with 1 digit is " & counter
repeat with i from 2 to (count cc's counts)
set end of output to "The number with " & i & " digits is " & (cc's counts's item i)
set counter to counter + (cc's counts's item i)
end repeat
set end of output to "The total number overall is " & counter
return join(output, linefeed)
end task
 
task()</syntaxhighlight>
 
=={{header|C}}==
The <code>count_colorful</code> function is based on [[#Phix|Phix]].
<langsyntaxhighlight lang="c">#include <locale.h>
#include <stdbool.h>
#include <stdio.h>
Line 126 ⟶ 487:
(end - start + 0.0) / CLOCKS_PER_SEC);
return 0;
}</langsyntaxhighlight>
 
{{out>@TIO.RUN}}
<pre>
Colorful numbers less than 100:
Line 153 ⟶ 514:
Total: 57,256
 
Elapsed time: 0.024598031256 seconds</pre>
 
=={{header|C++}}==
<syntaxhighlight lang="c++">
 
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <vector>
 
std::vector<uint32_t> count(8, 0);
std::vector<bool> used(10, false);
uint32_t largest = 0;
 
bool is_colorful(const uint32_t& number) {
if ( number > 98'765'432 ) {
return false;
}
 
std::vector<uint32_t> digit_count(10, 0);
std::vector<uint32_t> digits(8, 0);
uint32_t number_digits = 0;
 
for ( uint32_t i = number; i > 0; i /= 10 ) {
uint32_t digit = i % 10;
if ( number > 9 && ( digit == 0 || digit == 1 ) ) {
return false;
}
if ( ++digit_count[digit] > 1 ) {
return false;
}
digits[number_digits++] = digit;
}
 
std::vector<uint32_t> products(36, 0);
for ( uint32_t i = 0, product_count = 0; i < number_digits; ++i ) {
for ( uint32_t j = i, product = 1; j < number_digits; ++j ) {
product *= digits[j];
for ( uint32_t k = 0; k < product_count; ++k ) {
if ( products[k] == product ) {
return false;
}
}
products[product_count++] = product;
}
}
return true;
}
 
void count_colorful(const uint32_t& taken, const uint32_t& number, const uint32_t& digits) {
if ( taken == 0 ) {
for ( uint32_t digit = 0; digit < 10; ++digit ) {
used[digit] = true;
count_colorful(digit < 2 ? 9 : 1, digit, 1);
used[digit] = false;
}
} else {
if ( is_colorful(number) ) {
++count[digits - 1];
if ( number > largest ) {
largest = number;
}
}
if ( taken < 9 ) {
for ( uint32_t digit = 2; digit < 10; ++digit ) {
if ( ! used[digit] ) {
used[digit] = true;
count_colorful(taken + 1, number * 10 + digit, digits + 1);
used[digit] = false;
}
}
}
}
}
 
int main() {
std::cout << "Colorful numbers less than 100:" << std::endl;
for ( uint32_t number = 0, count = 0; number < 100; ++number ) {
if ( is_colorful(number) ) {
std::cout << std::setw(2) << number << ( ++count % 10 == 0 ? "\n" : " ");
}
}
std::cout << "\n" << std::endl;
 
count_colorful(0, 0, 0);
std::cout << "Count of colorful numbers by number of digits:" << std::endl;
uint32_t total = 0;
for ( uint32_t digit = 0; digit < 8; ++digit ) {
std::cout << digit + 1 << ": " << count[digit] << std::endl;
total += count[digit];
}
std::cout << std::endl;
 
std::cout << "The largest possible colorful number is: " << largest << "\n" << std::endl;
std::cout << "The total number of colorful numbers is: " << total << std::endl;
}
</syntaxhighlight>
{{ out }}
<pre>
Colorful numbers less than 100:
0 1 2 3 4 5 6 7 8 9
23 24 25 26 27 28 29 32 34 35
36 37 38 39 42 43 45 46 47 48
49 52 53 54 56 57 58 59 62 63
64 65 67 68 69 72 73 74 75 76
78 79 82 83 84 85 86 87 89 92
93 94 95 96 97 98
 
Count of colorful numbers by number of digits:
1: 10
2: 56
3: 328
4: 1540
5: 5514
6: 13956
7: 21596
8: 14256
 
The largest possible colorful number is: 98746253
 
The total number of colorful numbers is: 57256
</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
 
 
<syntaxhighlight lang="Delphi">
procedure ShowColorfulNumbers(Memo: TMemo);
var I,P,Cnt,OldCnt,Start,Stop: integer;
var S: string;
var Largest: integer;
 
 
function IsColorful(N: integer): boolean;
var IA: TIntegerDynArray;
var PList: TList;
var I,J,D,P: integer;
begin
PList:=TList.Create;
try
Result:=False;
GetDigits(N,IA);
{Number of digits at a time}
for D:=1 to Length(IA) do
{For all digits in number}
for I:=High(IA) downto D-1 do
begin
P:=1;
{Product of digits in a group}
for J:=0 to D-1 do P:=P * IA[I-J];
{Has it already been used}
if PList.IndexOf(Pointer(P))>=0 then exit;
{Store in list}
PList.Add(Pointer(P));
end;
Result:=True;
finally PList.Free; end;
end;
 
 
begin
Cnt:=0; S:='';
Memo.Line.Add('Colorful Number less than 100');
for I:=0 to 100-1 do
if IsColorful(I) then
begin
Inc(Cnt);
S:=S+Format('%7D',[I]);
If (Cnt mod 5)=0 then S:=S+CRLF;
end;
Memo.Lines.Add(S);
Memo.Lines.Add('Count = '+IntToStr(Cnt));
for Largest:=98765432 downto 1 do
if IsColorful(Largest) then break;
Memo.Lines.Add('Largest Colorful Number = '+IntToStr(Largest));
 
Start:=0; Stop:=9;
Cnt:=0; OldCnt:=0;
for P:=1 to 8 do
begin
for I:=Start to Stop do
if IsColorful(I) then Inc(Cnt);
Memo.Lines.Add(Format('Colorful Numbers from %10.0n to %10.0n: %5D', [Start+0.0,Stop+0.0,Cnt-OldCnt]));
Start:=Stop+1;
Stop:=(Start*10)-1;
OldCnt:=Cnt;
end;
for I:=Stop+1 to Largest do
if IsColorful(I) then Inc(Cnt);
Memo.Lines.Add('Total All Colorful = '+IntToStr(Cnt));
end;
 
 
</syntaxhighlight>
{{out}}
<pre>
Colorful Numbers less than 100
0 1 2 3 4
5 6 7 8 9
23 24 25 26 27
28 29 32 34 35
36 37 38 39 42
43 45 46 47 48
49 52 53 54 56
57 58 59 62 63
64 65 67 68 69
72 73 74 75 76
78 79 82 83 84
85 86 87 89 92
93 94 95 96 97
98
Count = 66
 
Largest Colorful Number = 98746253
 
Colorful Numbers from 0 to 9: 10
Colorful Numbers from 10 to 99: 56
Colorful Numbers from 100 to 999: 328
Colorful Numbers from 1,000 to 9,999: 1540
Colorful Numbers from 10,000 to 99,999: 5514
Colorful Numbers from 100,000 to 999,999: 13956
Colorful Numbers from 1,000,000 to 9,999,999: 21596
Colorful Numbers from 10,000,000 to 99,999,999: 14256
Total All Colorful = 57256
Elapsed Time: 01:36.252 min
 
</pre>
 
 
=={{header|EasyLang}}==
{{trans|C}}
<syntaxhighlight>
func colorful n .
len digcnt[] 10
arrbase digcnt[] 0
len digits[] 8
m = n
while m > 0
d = m mod 10
if n > 9 and d <= 1
return 0
.
digcnt[d] += 1
if digcnt[d] > 1
return 0
.
ndigs += 1
digits[ndigs] = d
m = m div 10
.
len products[] 36
for i to ndigs
p = 1
for j = i to ndigs
p *= digits[j]
for k to prodcnt
if products[k] = p
return 0
.
.
prodcnt += 1
products[prodcnt] = p
.
.
return 1
.
len cnt[] 8
len used[] 10
arrbase used[] 0
largest = 0
proc cnt_colorful taken n digits . .
if taken = 0
for d = 0 to 9
used[d] = 1
h = 1
if d < 2
h = 9
.
cnt_colorful h d 1
used[d] = 0
.
return
.
if colorful n = 1
cnt[digits] += 1
largest = higher largest n
.
if taken < 9
for d = 2 to 9
if used[d] = 0
used[d] = 1
cnt_colorful (taken + 1) (n * 10 + d) (digits + 1)
used[d] = 0
.
.
.
.
print "Colorful numbers less than 100:"
for n = 0 to 99
if colorful n = 1
write n & " "
.
.
cnt_colorful 0 0 0
print "\n\nLargest colorful number:" & largest
#
print "\nCount of colorful numbers by number of digits:\n"
for d to 8
print d & " " & cnt[d]
total += cnt[d]
.
print "\nTotal: " & total
</syntaxhighlight>
{{out}}
<pre>
Colorful numbers less than 100:
0 1 2 3 4 5 6 7 8 9 23 24 25 26 27 28 29 32 34 35 36 37 38 39 42 43 45 46 47 48 49 52 53 54 56 57 58 59 62 63 64 65 67 68 69 72 73 74 75 76 78 79 82 83 84 85 86 87 89 92 93 94 95 96 97 98
 
Largest colorful number:98746253
 
Count of colorful numbers by number of digits:
 
1 10
2 56
3 328
4 1540
5 5514
6 13956
7 21596
8 14256
 
Total: 57256
</pre>
 
=={{header|Factor}}==
{{works with|Factor|0.99 2021-06-02}}
<langsyntaxhighlight lang="factor">USING: assocs grouping grouping.extras io kernel literals math
math.combinatorics math.ranges prettyprint project-euler.common
sequences sequences.extras sets ;
Line 187 ⟶ 881:
"Count of colorful numbers by number of digits:" print
8 [1..b] [ oom-count ] zip-with dup .
"Total: " write values sum .</langsyntaxhighlight>
{{out}}
<pre>
Line 214 ⟶ 908:
}
Total: 57256
</pre>
 
=={{header|Go}}==
{{trans|Phix}}
{{libheader|Go-rcu}}
<syntaxhighlight lang="go">package main
 
import (
"fmt"
"rcu"
"strconv"
)
 
func isColorful(n int) bool {
if n < 0 {
return false
}
if n < 10 {
return true
}
digits := rcu.Digits(n, 10)
for _, d := range digits {
if d == 0 || d == 1 {
return false
}
}
set := make(map[int]bool)
for _, d := range digits {
set[d] = true
}
dc := len(digits)
if len(set) < dc {
return false
}
for k := 2; k <= dc; k++ {
for i := 0; i <= dc-k; i++ {
prod := 1
for j := i; j <= i+k-1; j++ {
prod *= digits[j]
}
if ok := set[prod]; ok {
return false
}
set[prod] = true
}
}
return true
}
 
var count = make([]int, 9)
var used = make([]bool, 11)
var largest = 0
 
func countColorful(taken int, n string) {
if taken == 0 {
for digit := 0; digit < 10; digit++ {
dx := digit + 1
used[dx] = true
t := 1
if digit < 2 {
t = 9
}
countColorful(t, string(digit+48))
used[dx] = false
}
} else {
nn, _ := strconv.Atoi(n)
if isColorful(nn) {
ln := len(n)
count[ln]++
if nn > largest {
largest = nn
}
}
if taken < 9 {
for digit := 2; digit < 10; digit++ {
dx := digit + 1
if !used[dx] {
used[dx] = true
countColorful(taken+1, n+string(digit+48))
used[dx] = false
}
}
}
}
}
 
func main() {
var cn []int
for i := 0; i < 100; i++ {
if isColorful(i) {
cn = append(cn, i)
}
}
fmt.Println("The", len(cn), "colorful numbers less than 100 are:")
for i := 0; i < len(cn); i++ {
fmt.Printf("%2d ", cn[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
 
countColorful(0, "")
fmt.Println("\n\nThe largest possible colorful number is:")
fmt.Println(rcu.Commatize(largest))
 
fmt.Println("\nCount of colorful numbers for each order of magnitude:")
pow := 10
for dc := 1; dc < len(count); dc++ {
cdc := rcu.Commatize(count[dc])
pc := 100 * float64(count[dc]) / float64(pow)
fmt.Printf(" %d digit colorful number count: %6s - %7.3f%%\n", dc, cdc, pc)
if pow == 10 {
pow = 90
} else {
pow *= 10
}
}
 
sum := 0
for _, c := range count {
sum += c
}
fmt.Printf("\nTotal colorful numbers: %s\n", rcu.Commatize(sum))
}</syntaxhighlight>
 
{{out}}
<pre>
The 66 colorful numbers less than 100 are:
0 1 2 3 4 5 6 7 8 9
23 24 25 26 27 28 29 32 34 35
36 37 38 39 42 43 45 46 47 48
49 52 53 54 56 57 58 59 62 63
64 65 67 68 69 72 73 74 75 76
78 79 82 83 84 85 86 87 89 92
93 94 95 96 97 98
 
The largest possible colorful number is:
98,746,253
 
Count of colorful numbers for each order of magnitude:
1 digit colorful number count: 10 - 100.000%
2 digit colorful number count: 56 - 62.222%
3 digit colorful number count: 328 - 36.444%
4 digit colorful number count: 1,540 - 17.111%
5 digit colorful number count: 5,514 - 6.127%
6 digit colorful number count: 13,956 - 1.551%
7 digit colorful number count: 21,596 - 0.240%
8 digit colorful number count: 14,256 - 0.016%
 
Total colorful numbers: 57,256
</pre>
 
=={{header|Haskell}}==
{{incorrect|Haskell|9876543210 is not a Colorful number; nor is 98765432: <nowiki>6×5×4 == 5×4×3×2 == 120</nowiki>}}
<langsyntaxhighlight lang="haskell">import Data.List ( nub )
import Data.List.Split ( divvy )
import Data.Char ( digitToInt )
Line 240 ⟶ 1,085:
 
solution2 :: Integer
solution2 = head $ filter isColourful [98765432, 98765431 ..]</langsyntaxhighlight>
{{out}}
<pre>[0,1,2,3,4,5,6,7,8,9,10,23,24,25,26,27,28,29,32,34,35,36,37,38,39,42,43,45,46,47,48,49,52,53,54,56,57,58,59,62,63,64,65,67,68,69,72,73,74,75,76,78,79,82,83,84,85,86,87,89,92,93,94,95,96,97,98](solution1)
98765432(solution2)</pre>
 
=={{header|Haskell (alternate version)}}==
An alternate Haskell version, which some may consider to be in a more idiomatic style. No attempt at optimization has been made, so we don't attempt the stretch goals.
<syntaxhighlight lang="haskell">import Data.List (inits, nub, tails, unfoldr)
 
-- Non-empty subsequences containing only consecutive elements from the
-- argument. For example:
--
-- consecs [1,2,3] => [[1],[1,2],[1,2,3],[2],[2,3],[3]]
consecs :: [a] -> [[a]]
consecs = drop 1 . ([] :) . concatMap (drop 1 . inits) . tails
 
-- The list of digits in the argument, from least to most significant. The
-- number 0 is represented by the empty list.
toDigits :: Int -> [Int]
toDigits = unfoldr step
where step 0 = Nothing
step n = let (q, r) = n `quotRem` 10 in Just (r, q)
 
-- True if and only if all the argument's elements are distinct.
allDistinct :: [Int] -> Bool
allDistinct ns = length ns == length (nub ns)
 
-- True if and only if the argument is a colorful number.
isColorful :: Int -> Bool
isColorful = allDistinct . map product . consecs . toDigits
 
main :: IO ()
main = do
let smalls = filter isColorful [0..99]
putStrLn $ "Small colorful numbers: " ++ show smalls
 
let start = 98765432
largest = head $ dropWhile (not . isColorful) [start, start-1 ..]
putStrLn $ "Largest colorful number: " ++ show largest</syntaxhighlight>
{{out}}
<pre>
$ colorful
Small colorful numbers: [0,1,2,3,4,5,6,7,8,9,23,24,25,26,27,28,29,32,34,35,36,37,38,39,42,43,45,46,47,48,49,52,53,54,56,57,58,59,62,63,64,65,67,68,69,72,73,74,75,76,78,79,82,83,84,85,86,87,89,92,93,94,95,96,97,98]
Largest colorful number: 98746253
</pre>
 
=={{header|J}}==
 
<langsyntaxhighlight Jlang="j"> colorful=: {{(-:~.);<@(*/\)\. 10 #.inv y}}"0
I.colorful i.100
0 1 2 3 4 5 6 7 8 9 23 24 25 26 27 28 29 32 34 35 36 37 38 39 42 43 45 46 47 48 49 52 53 54 56 57 58 59 62 63 64 65 67 68 69 72 73 74 75 76 78 79 82 83 84 85 86 87 89 92 93 94 95 96 97 98
Line 264 ⟶ 1,150:
7 14256
#C
57256</langsyntaxhighlight>
 
(Note that 0, here is a different order of magnitude than 1.)
Line 270 ⟶ 1,156:
=={{header|Java}}==
{{trans|C}}
<langsyntaxhighlight lang="java">public class ColorfulNumbers {
private int count[] = new int[8];
private boolean used[] = new boolean[10];
Line 353 ⟶ 1,239:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 379 ⟶ 1,265:
 
Total: 57,256
</pre>
 
=={{header|jq}}==
''' Generic Utility Functions'''
<syntaxhighlight lang=jq>
# Uncomment for gojq
# def _nwise($n):
# def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end;
# n;
 
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
 
# Generate a stream of the permutations of the input array.
def permutations:
if length == 0 then []
else
range(0;length) as $i
| [.[$i]] + (del(.[$i])|permutations)
end ;
</syntaxhighlight>
'''Colorful Numbers'''
<syntaxhighlight lang=jq>
def isColorful:
def digits: [tostring | explode[] | [.] | implode | tonumber];
 
if . < 0 then false
elif . < 10 then true
else . as $n
| digits as $digits
| if any($digits[]; . == 0 or . == 1) then false
else ($digits|unique) as $set
| ($digits|length) as $dc
| if ($set|length) < $dc then false
else label $out
| foreach range(2; $dc) as $k ({$set};
foreach range(0; $dc-$k+1) as $i (.;
(reduce range($i; $i+$k) as $j (1; . * $digits[$j])) as $prod
| if .set|index($prod) then .return = 0, break $out
else .set += [$prod]
end ;
. );
select(.return) ) // null
| if .return == 0 then false else true end
end
end
end;
 
# Emit a stream of colorfuls in range(a;b)
def colorfuls(a;b):
range(a;b) | select(isColorful);
 
</syntaxhighlight>
'''The Tasks'''
<syntaxhighlight lang=jq>
 
def task($n):
[colorfuls(0; $n)]
| "The \(length) colorful numbers less than \($n) are:",
(_nwise($10) | map(lpad(4)) | join(" ")) ;
 
def largestColorful:
[[range(2;10)] | permutations | join("") | tonumber | select(isColorful)] | max;
 
# Emit a JSON object giving the counts by number of digits
def classifyColorful:
def nonTrivialCandidates:
[range(2; 10)]
| range(1; 9) as $length
| combinations($length)
| join("")
| tonumber;
reduce (0,1,nonTrivialCandidates) as $i ({};
if $i|isColorful
then .[$i|tostring|length|tostring] += 1
else .
end);
task(100),
"",
"The largest possible colorful number is \(largestColorful)."
"",
"The counts of colorful numbers by number of digits are:",
(classifyColorful
| (., "\nTotal: \([.[]]|add)"))
</syntaxhighlight>
 
'''Invocation''': jq -ncr -f colorful.jq
 
{{Output}}
<pre>
The 66 colorful numbers less than 100 are:
0 1 2 3 4 5 6 7 8 9
23 24 25 26 27 28 29 32 34 35
36 37 38 39 42 43 45 46 47 48
49 52 53 54 56 57 58 59 62 63
64 65 67 68 69 72 73 74 75 76
78 79 82 83 84 85 86 87 89 92
93 94 95 96 97 98
 
The largest possible colorful number is 98746253.
 
The counts of colorful numbers by number of digits are:
{"1":10,"2":56,"3":328,"4":1540,"5":5514,"6":13956,"7":21596,"8":14256}
 
Total: 57256
</pre>
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">largest = 0
{{incomplete|Julia|Missing third part of task - Find largest possible colorful number.<br>}}
 
<lang julia>function iscolorful(n, base=10)
function iscolorful(n, base=10)
0 <= n < 10 && return true
dig = digits(n, base=base)
Line 392 ⟶ 1,384:
p in products && return false
push!(products, p)
end
if n > largest
global largest = n
end
return true
end
 
function testcolorfuls()
println("Colorful numbers for 1:25, 26:50, 51:75, and 76:100:")
Line 409 ⟶ 1,404:
println("The count of colorful numbers between $j and $k is $n.")
end
println("The largest possible colorful number is $largest.")
println("The total number of colorful numbers is $csum.")
end
 
testcolorfuls()
</langsyntaxhighlight>{{out}}
<pre>
Colorful numbers for 1:25, 26:50, 51:75, and 76:100:
1 2 3 4 5 6 7 8 9 23 24 25
26 27 28 29 32 34 35 36 37 38 39 42 43 45 46 47 48 49
52 53 54 56 57 58 59 62 63 64 65 67 68 69 72 73 74 75
76 78 79 82 83 84 85 86 87 89 92 93 94 95 96 97 98
The count of colorful numbers between 0 and 9 is 10.
The count of colorful numbers between 10 and 99 is 56.
Line 428 ⟶ 1,424:
The count of colorful numbers between 1000000 and 9999999 is 21596.
The count of colorful numbers between 10000000 and 99999999 is 14256.
The largest possible colorful number is 98746253.
The total number of colorful numbers is 57256.
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">ClearAll[ColorfulNumberQ]
ColorfulNumberQ[n_Integer?NonNegative] := Module[{digs, parts},
If[n > 98765432,
False
,
digs = IntegerDigits[n];
parts = Partition[digs, #, 1] & /@ Range[1, Length[digs]];
parts //= Catenate;
parts = Times @@@ parts;
DuplicateFreeQ[parts]
]
]
Multicolumn[Select[Range[99], ColorfulNumberQ], Appearance -> "Horizontal"]
 
sel = Union[FromDigits /@ Catenate[Permutations /@ Subsets[Range[2, 9], {1, \[Infinity]}]]];
sel = Join[sel, {0, 1}];
cns = Select[sel, ColorfulNumberQ];
 
Max[cns]
 
Tally[IntegerDigits/*Length /@ cns] // Grid
 
Length[cns]</syntaxhighlight>
{{out}}
<pre>1 2 3 4 5 6 7 8
9 23 24 25 26 27 28 29
32 34 35 36 37 38 39 42
43 45 46 47 48 49 52 53
54 56 57 58 59 62 63 64
65 67 68 69 72 73 74 75
76 78 79 82 83 84 85 86
87 89 92 93 94 95 96 97
98
 
98746253
 
1 10
2 56
3 328
4 1540
5 5514
6 13956
7 21596
8 14256
 
57256</pre>
 
=={{header|Nim}}==
{{trans|Python}}
<syntaxhighlight lang="Nim">import std/[math, intsets, strformat]
 
func digits(n: Natural): seq[int] =
## Return the digits of "n" in reverse order.
var n = n
while true:
result.add n mod 10
n = n div 10
if n == 0: break
 
var largest = 0
 
proc isColorful(n: Natural): bool =
## Return true if "n" is colorful.
if n in 0..9: return true
let digSeq = n.digits
var digSet: set[0..9]
for d in digSeq:
if d <= 1 or d in digSet:
return false
digSet.incl d
var products = digSeq.toIntSet()
for i in 0..<digSeq.high:
for j in (i + 1)..digSeq.high:
let p = prod(digSeq.toOpenArray(i, j))
if p in products:
return false
products.incl p
if n > largest: largest = n
result = true
 
echo "Colorful numbers for 1:25, 26:50, 51:75, and 76:100:"
for i in countup(1, 100, 25):
for j in 0..24:
if isColorful(i + j):
stdout.write &"{i + j: 5}"
echo()
 
echo()
var csum = 0
for i in 0..7:
let j = if i == 0: 0 else: 10^i
let k = 10^(i+1) - 1
var n = 0
for x in j..k:
if x.isColorful: inc n
inc csum, n
echo &"The count of colorful numbers between {j} and {k} is {n}."
 
echo()
echo &"The largest possible colorful number is {largest}."
echo &"The total number of colorful numbers is {csum}."
</syntaxhighlight>
 
{{out}}
<pre>Colorful numbers for 1:25, 26:50, 51:75, and 76:100:
1 2 3 4 5 6 7 8 9 23 24 25
26 27 28 29 32 34 35 36 37 38 39 42 43 45 46 47 48 49
52 53 54 56 57 58 59 62 63 64 65 67 68 69 72 73 74 75
76 78 79 82 83 84 85 86 87 89 92 93 94 95 96 97 98
 
The count of colorful numbers between 0 and 9 is 10.
The count of colorful numbers between 10 and 99 is 56.
The count of colorful numbers between 100 and 999 is 328.
The count of colorful numbers between 1000 and 9999 is 1540.
The count of colorful numbers between 10000 and 99999 is 5514.
The count of colorful numbers between 100000 and 999999 is 13956.
The count of colorful numbers between 1000000 and 9999999 is 21596.
The count of colorful numbers between 10000000 and 99999999 is 14256.
 
The largest possible colorful number is 98746253.
The total number of colorful numbers is 57256.
</pre>
 
=={{header|Pascal}}==
==={{header|Free Pascal}}===
I've created a lexical permutation of [2,3,4,5,6,7,8,9] which results in 40320 arrangements.<br>
So 0,1 are missing. The test of 3 digits is simple a test of the first three digits of these arrangments every delta = (8-3)! = 120 (for one digit = (8-1)! = 5040 ).<BR>
At home, the [[#C|C]]-Version compiled with -Ofast is still faster with best 15.03 ms vs 18ms of my version<br>But such short timings differ extrem from run to run.
 
<syntaxhighlight lang="pascal">{$IFDEF FPC}
{$mode Delphi}
{$Optimization ON,All}
{$Coperators ON}
{$ENDIF}
{$IFDEF WINDOWS}
{$APPTYPE CONSOLE}
{$ENDIF}
uses
sysutils;
const
EightFak = 1*2*3*4*5*6*7*8;
type
tDgt = Int8;
tpDgt = pInt8;
tDgtfield = array[0..7] of tdgt;
tpDgtfield = ^tDgtfield;
tPermfield = tDgtfield;
tAllPermDigits = array[0..EightFak] of tDgtfield;
tMarkNotColorful = array[0..EightFak-1] of byte;
 
tDat = Uint32;
tusedMultiples = array[0..8*9 DIV 2-2] of tDat;
var
AllPermDigits :tAllPermDigits;
MarkNotColorful:tMarkNotColorful;
permcnt,
totalCntColorFul,CntColorFul : Int32;
 
procedure PermLex(n: Int32;StartVal:Int8);
var
Perm : tPermField;
k,j : Int32;
temp: tDgt;
pDat :tpDgt;
begin
For j := 0 to n-1 do
Perm[j]:= j+StartVal;
permcnt := 0;
dec(n);
repeat
AllPermDigits[permcnt] := Perm;
inc(permcnt);
k := N-1;
pDat := @Perm[k];
while (pDat[0]> pDat[1]) And (k >=Low(Perm) ) do
begin
dec(pDat);
dec(k);
end;
 
if k >= Low(Perm) then
begin
j := N;
pDat := @Perm[j];
temp := Perm[k];
while (temp > pDat[0]) And (J >K) do
begin
dec(j);
dec(pDat);
end;
 
Perm[k] := pDat[0];
pDat[0] := temp;
j := N;
pDat := @Perm[j];
Inc(k);
 
while j>k do
begin
temp := pDat[0];
pDat[0] := Perm[k];
Perm[k] := temp;
 
dec(j);
dec(pDat);
inc(k);
end;
end
else
break;
until false;
end;
 
procedure OutNum(const num:tPermfield;dgtCnt: Int32);
var
i : integer;
Begin
For i := 0 to dgtcnt-1 do
write(num[i]);
writeln;
end;
 
function isAlreadyExisting(var uM :tusedMultiples; maxIdx : Int32;dat :tDat):boolean;
var
I : Int32;
begin
if maxIdx >= 0 then
begin
i := maxIdx;
repeat
if dat = uM[i] then
EXIT(true);
Dec(i);
until i <0;
end;
uM[maxIdx+1]:= dat;
result := false;
end;
 
function CalcValue(pDgtfield : tpDgtfield;TestDgtCnt:Int32):int32;
begin
result := 1;
repeat
result *=pDgtfield[TestDgtCnt];
dec(TestDgtCnt);
until TestDgtCnt <0;
end;
function isCheckColorful(dgtCnt: NativeInt;idx:Int32):boolean;
var
usedMultiples : tusedMultiples;
pDgtfield : ^tDgtfield;
TestDgtCnt,StartIdx,value,maxIdx : Int32;
begin
//needn't to test product of all digits.It's a singular max value
dec(dgtCnt);
pDgtfield := @AllPermDigits[idx];
maxIdx := -1;
 
//multiples of TestDgtCnt digits next to one another
For TestDgtCnt := 0 to dgtCnt do
begin
For StartIdx := 0 to dgtCnt-TestDgtCnt do
begin
value := CalcValue(@pDgtfield[StartIdx],TestDgtCnt);
// value := 1; For l := 0 to TestDgtCnt do value *=pDgtfield[StartIdx+l];
if isAlreadyExisting(usedMultiples,maxIdx,value) then
EXIT(false);
inc(MaxIdx);
end;
end;
inc(totalCntColorFul);
inc(CntColorFul);
result := true;
end;
 
procedure CheckDgtCnt(dgtCnt,delta:Int32);
var
i,j : int32;
begin
i := 0;
CntColorFul := 0;
if dgtCnt = 1 then
CntColorFul := 2;//0,1
 
if delta = 1 then
begin
For i := i to EightFak-1 do
IF (MarkNotColorful[i]=0) AND not isCheckColorful(dgtCnt,i)then
MarkNotColorful[i] := dgtcnt;
end
else
Begin
if dgtcnt<3 then
//always colorful
begin
repeat
isCheckColorful(dgtCnt,i);
inc(i,delta);
until i>EightFak-1;
end
else
begin
repeat
IF (MarkNotColorful[i]=0) AND not isCheckColorful(dgtCnt,i) then
begin
//mark a range as not colorful
j := i+delta-1;
repeat
MarkNotColorful[j] := dgtcnt;
dec(j);
until j < i;
end;
inc(i,delta);
until i>EightFak-1;
end;
end;
end;
 
var
T0 : Int64;
i,j,delta: INteger;
Begin
T0 := GetTickCount64;
PermLex(8,2);
//takes ~1 ms til here
delta := 15;
writeln('First colorful numbers less than 100');
For i := 0 to 9 do
Begin
write(i:4);
dec(delta);
end;
For i := 2 to 9 do
For j := 2 to 9 do
if j<> i then
begin
//write(i:3,j);
dec(delta);
if delta = 0 then
begin
delta:= 15;
Writeln;
end;
end;
writeln;
writeln;
Writeln(' digits count of colorful numbers');
totalCntColorFul := 2;//0,1,
delta := EightFak-1;
delta := (delta+1) DIV 8;
j := 7;
repeat
CheckDgtCnt(8-j,delta);
writeln(8-j:10,CntColorFul:10);
if j = 0 then
BREAK;
delta := delta DIV j;
dec(j);
until false;
Writeln;
Writeln('Total number of colorful numbers: ',totalCntColorFul);
Write('Highest Value :');
For i := High(AllPermDigits) downto low(AllPermDigits) do
if MarkNotColorful[i] = 0 then
Begin
OutNum(AllPermDigits[i],8);
BREAK;
end;
 
Writeln('Runtime in ms ',GetTickCount64-T0);
end.
</syntaxhighlight>
{{out|@TIO.RUN}}
<pre>
First colorful numbers less than 100
0 1 2 3 4 5 6 7 8 9 23 24 25 26 27
28 29 32 34 35 36 37 38 39 42 43 45 46 47 48
49 52 53 54 56 57 58 59 62 63 64 65 67 68 69
72 73 74 75 76 78 79 82 83 84 85 86 87 89 92
93 94 95 96 97 98
 
digits count of colorful numbers
1 10
2 56
3 328
4 1540
5 5514
6 13956
7 21596
8 14256
 
Total number of colorful numbers: 57256
Highest Value :98746253
 
Runtime in ms 38 (= best TIO.Run up to 51 ms )
Runtime in ms 18 (= best up to 27 ms @home )
</pre>
 
=={{header|Perl}}==
{{trans|Raku}}
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
Line 464 ⟶ 1,864:
my $total= 10;
map { is_colorful(join '', @$_) and $total++ } map { permutations $_ } combinations [2..9], $_ for 2..8;
say "Total colorful numbers: $total";</langsyntaxhighlight>
{{out}}
<pre>Colorful numbers less than 100:
Line 482 ⟶ 1,882:
{{libheader|Phix/online}}
You can run this online [http://phix.x10.mx/p2js/colourful.htm here].
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">colourful</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
Line 546 ⟶ 1,946:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\nTotal colourful numbers: %,d\n"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #000000;">count</span><span style="color: #0000FF;">))</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 571 ⟶ 1,971:
Total colourful numbers: 57,256
"1.9s"
</pre>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">colorful_number(N) =>
N < 10 ;
(X = N.to_string,
X.len <= 8,
not membchk('0',X),
not membchk('1',X),
distinct(X),
[prod(S.map(to_int)) : S in findall(S,(append(_,S,_,X),S != [])) ].distinct).
 
distinct(L) =>
L.len == L.remove_dups.len.</syntaxhighlight>
 
'''All colorful numbers <= 100.'''
<syntaxhighlight lang="picat">main =>
Colorful = [N : N in 0..100, colorful_number(N)],
Len = Colorful.len,
foreach({C,I} in zip(Colorful,1..Len))
printf("%2d%s",C, cond(I mod 10 == 0, "\n"," "))
end,
nl,
println(len=Len)</syntaxhighlight>
 
{{out}}
<pre> 0 1 2 3 4 5 6 7 8 9
23 24 25 26 27 28 29 32 34 35
36 37 38 39 42 43 45 46 47 48
49 52 53 54 56 57 58 59 62 63
64 65 67 68 69 72 73 74 75 76
78 79 82 83 84 85 86 87 89 92
93 94 95 96 97 98
len = 66</pre>
 
'''Largest colorful number.'''
<syntaxhighlight lang="picat">main =>
N = 98765431,
Found = false,
while (Found == false)
if colorful_number(N) then
println(N),
Found := true
end,
N := N - 1
end.</syntaxhighlight>
 
{{out}}
<pre>98746253</pre>
 
'''Count of colorful numbers in each magnitude and of total colorful numbers.'''
<syntaxhighlight lang="picat">main =>
TotalC = 0,
foreach(I in 1..8)
C = 0,
printf("Digits %d: ", I),
foreach(N in lb(I)..ub(I))
if colorful_number(N) then
C := C + 1
end
end,
println(C),
TotalC := TotalC + C
end,
println(total=TotalC),
nl.
 
% Lower and upper bounds.
% For N=3: lb=123 and ub=987
lb(N) = cond(N < 2, 0, [I.to_string : I in 1..N].join('').to_int).
ub(N) = [I.to_string : I in 9..-1..9-N+1].join('').to_int.</syntaxhighlight>
 
{{out}}
<pre>Digits 1: 10
Digits 2: 56
Digits 3: 328
Digits 4: 1540
Digits 5: 5514
Digits 6: 13956
Digits 7: 21596
Digits 8: 14256
total = 57256</pre>
 
=={{header|Python}}==
<syntaxhighlight lang="python">from math import prod
 
largest = [0]
 
def iscolorful(n):
if 0 <= n < 10:
return True
dig = [int(c) for c in str(n)]
if 1 in dig or 0 in dig or len(dig) > len(set(dig)):
return False
products = list(set(dig))
for i in range(len(dig)):
for j in range(i+2, len(dig)+1):
p = prod(dig[i:j])
if p in products:
return False
products.append(p)
 
largest[0] = max(n, largest[0])
return True
 
print('Colorful numbers for 1:25, 26:50, 51:75, and 76:100:')
for i in range(1, 101, 25):
for j in range(25):
if iscolorful(i + j):
print(f'{i + j: 5,}', end='')
print()
 
csum = 0
for i in range(8):
j = 0 if i == 0 else 10**i
k = 10**(i+1) - 1
n = sum(iscolorful(x) for x in range(j, k+1))
csum += n
print(f'The count of colorful numbers between {j} and {k} is {n}.')
 
print(f'The largest possible colorful number is {largest[0]}.')
print(f'The total number of colorful numbers is {csum}.')
</syntaxhighlight>{{out}}
<pre>
Colorful numbers for 1:25, 26:50, 51:75, and 76:100:
1 2 3 4 5 6 7 8 9 23 24 25
26 27 28 29 32 34 35 36 37 38 39 42 43 45 46 47 48 49
52 53 54 56 57 58 59 62 63 64 65 67 68 69 72 73 74 75
76 78 79 82 83 84 85 86 87 89 92 93 94 95 96 97 98
The count of colorful numbers between 0 and 9 is 10.
The count of colorful numbers between 10 and 99 is 56.
The count of colorful numbers between 100 and 999 is 328.
The count of colorful numbers between 1000 and 9999 is 1540.
The count of colorful numbers between 10000 and 99999 is 5514.
The count of colorful numbers between 100000 and 999999 is 13956.
The count of colorful numbers between 1000000 and 9999999 is 21596.
The count of colorful numbers between 10000000 and 99999999 is 14256.
The largest possible colorful number is 98746253.
The total number of colorful numbers is 57256.
</pre>
 
=={{header|Raku}}==
<syntaxhighlight lang="raku" perl6line>sub is-colorful (Int $n) {
return True if 0 <= $n <= 9;
return False if $n.contains(0) || $n.contains(1) || $n < 0;
Line 587 ⟶ 2,126:
}
 
put "Colorful numbers less than 100:\n" ~ (^100).racehyper.grep( &is-colorful).batch(10)».fmt("%2d").join: "\n";
 
my ($start, $total) = 23456789, 10;
Line 600 ⟶ 2,139:
for 2..8 {
put "$_ digit colorful number count: ",
my $c = +(flat $start.comb.combinations($_).map: {.permutations».join».Int}).racehyper.grep( &is-colorful ),
" - {($c / (exp($_,10) - exp($_-1,10) ) * 100).round(.001)}%";
$total += $c;
}
 
say "\nTotal colorful numbers: $total";</langsyntaxhighlight>
{{out}}
<pre>Colorful numbers less than 100:
Line 629 ⟶ 2,168:
 
Total colorful numbers: 57256</pre>
 
=={{header|RPL}}==
We have assumed that the largest colored number has 8 digits. This means we only need to check the permutations of 98765432. Brute force is here used, generating these permutations - and many other numbers - through decrementation by 9. Before testing the colorfulness, the sum of the digits of the generated number is compared to that of 98765432. This improves execution time a little bit.
 
If the search had been unsuccessful, we would have tested the different possibilities of 7-digit pandigital numbers - but luckily it was not necessary.
{{works with|HP|48G}}
{| class="wikitable" ≪
! RPL code
! Comment
|-
|
≪ →STR DUP SIZE → num dig
≪ '''CASE'''
dig 1 == '''THEN''' 1 '''END'''
num "0" POS num "1" POS OR '''THEN''' 0 '''END'''
1 SF
{ } 1 dig '''FOR''' j num j DUP SUB STR→ + '''NEXT'''
DUP SORT ΔLIST 1 + ΠLIST NOT '''THEN''' DROP 0 '''END'''
DUP
1 dig 1 - '''FOR''' k
1 dig k - '''FOR''' c
OVER c DUP k + SUB ΠLIST
'''IF''' DUP2 POS
'''THEN''' DROP 1 CF dig DUP 'c' STO 'k' STO
'''ELSE''' + '''END'''
'''NEXT NEXT'''
DROP2 1 FS? '''END'''
≫ ≫ '<span style="color:blue">COLOR?</span>' STO
|
<span style="color:blue">COLOR?</span> ( num → boolean )
if num has only 1 digit then return true
if num contains 0 or 1 then return false
color = true
convert n into a list of digits
if 2 digits are identical then return false
list of products = list of digits
for k = 1 to ndig-1
for c = 1 to ndig-k
p = digit[c]*..*digit[c+k]
if p in list of products
then color = false, exit loops
else append p to list of products
end loops
clean stack, return color
|}
≪ →STR 0
1 3 PICK SIZE '''FOR''' j
OVER j DUP SUB NUM +
'''NEXT''' SWAP DROP
≫ '<span style="color:blue">DSTAMP</span>' STO
≪ { }
1 100 '''FOR''' j IF j <span style="color:blue">COLOR?</span> '''THEN''' + '''END NEXT'''
98765432 DUP <span style="color:blue">DSTAMP</span> SWAP
'''WHILE''' DUP <span style="color:blue">COLOR?</span> NOT '''REPEAT'''
'''DO''' 9 - '''UNTIL''' DUP2 <span style="color:blue">DSTAMP</span> == '''END'''
'''END''' SWAP DROP
≫ '<span style="color:blue">TASK</span>' STO
{{out}}
<pre>
2: { 1 2 3 4 5 6 7 8 9 23 24 25 26 27 28 29 32 34 35 36 37 38 39 42 43 45 46 47 48 49 52 53 54 56 57 58 59 62 63 64 65 67 68 69 72 73 74 75 76 78 79 82 83 84 85 86 87 89 92 93 94 95 96 97 98 }
1: 98746253
</pre>
Largest colorful number found in 10 minutes 22 seconds on a HP-48G.
 
 
=={{header|Ruby}}==
All colorful candidates larger than 1 digit must be a permutation of digits [2,3,4,5,6,7,8,9], so test only those:
<syntaxhighlight lang="ruby">def colorful?(ar)
products = []
(1..ar.size).all? do |chunk_size|
ar.each_cons(chunk_size) do |chunk|
product = chunk.inject(&:*)
return false if products.include?(product)
products << product
end
end
end
 
below100 = (0..100).select{|n| colorful?(n.digits)}
puts "The colorful numbers less than 100 are:", below100.join(" "), ""
puts "Largest colorful number: #{(98765432.downto(1).detect{|n| colorful?(n.digits) })}", ""
 
total = 0
(1..8).each do |numdigs|
digits = (numdigs == 1 ? (0..9).to_a : (2..9).to_a)
count = digits.permutation(numdigs).count{|perm| colorful?(perm)}
puts "#{numdigs} digit colorful numbers count: #{count}"
total += count
end
 
puts "\nTotal colorful numbers: #{total}"
</syntaxhighlight>
{{out}}
<pre>
The colorful numbers less than 100 are:
0 1 2 3 4 5 6 7 8 9 23 24 25 26 27 28 29 32 34 35 36 37 38 39 42 43 45 46 47 48 49 52 53 54 56 57 58 59 62 63 64 65 67 68 69 72 73 74 75 76 78 79 82 83 84 85 86 87 89 92 93 94 95 96 97 98
 
Largest colorful number: 98746253
 
1 digit colorful numbers count: 10
2 digit colorful numbers count: 56
3 digit colorful numbers count: 328
4 digit colorful numbers count: 1540
5 digit colorful numbers count: 5514
6 digit colorful numbers count: 13956
7 digit colorful numbers count: 21596
8 digit colorful numbers count: 14256
 
Total colorful numbers: 57256
</pre>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">use core::cmp::max;
use std::collections::HashSet;
 
fn to_digits(mut n: u64, base: u64) -> Vec<u64> {
if n == 0 {
return [0].to_vec();
}
let mut v: Vec<u64> = Vec::new();
while n > 0 {
let d = n % base;
n /= base;
v.push(d);
}
return v;
}
 
fn is_colorful(n: u64) -> bool {
if &n > &9 {
let dig: Vec<u64> = to_digits(n, 10);
if dig.contains(&1) || dig.contains(&0) {
return false;
}
let mut products: HashSet<u64> = HashSet::new();
for i in 0..dig.len() {
if products.contains(&dig[i]) {
return false;
}
products.insert(dig[i]);
}
for i in 0..dig.len() {
for j in i+2..dig.len()+1 {
let p: u64 = (dig[i..j]).iter().product();
if products.contains(&p) {
return false;
}
products.insert(p);
}
}
}
return true;
}
 
fn main() {
println!("Colorful numbers for 1:25, 26:50, 51:75, and 76:100:");
for i in (1..101).step_by(25) {
for j in 0..25 {
if is_colorful(i + j) {
print!("{:5}", i + j);
}
}
println!();
}
println!();
 
let mut csum: u64 = 0;
let mut largest: u64 = 0;
let mut n: u64;
for i in 0..8 {
let j: u64 = { if i == 0 { 0 } else { 10_u64.pow(i) } };
let k: u64 = 10_u64.pow(i + 1) - 1;
n = 0;
for x in j..k+1 {
if is_colorful(x) {
largest = max(largest, x);
n += 1;
}
}
println!("The count of colorful numbers within the interval [{j}, {k}] is {n}.");
csum += n;
}
println!("The largest possible colorful number is {largest}.");
println!("The total number of colorful numbers is {csum}.")
}
</syntaxhighlight>{{out}}
<pre>
Colorful numbers for 1:25, 26:50, 51:75, and 76:100:
1 2 3 4 5 6 7 8 9 23 24 25
26 27 28 29 32 34 35 36 37 38 39 42 43 45 46 47 48 49
52 53 54 56 57 58 59 62 63 64 65 67 68 69 72 73 74 75
76 78 79 82 83 84 85 86 87 89 92 93 94 95 96 97 98
 
The count of colorful numbers within the interval [0, 9] is 10.
The count of colorful numbers within the interval [10, 99] is 56.
The count of colorful numbers within the interval [100, 999] is 328.
The count of colorful numbers within the interval [1000, 9999] is 1540.
The count of colorful numbers within the interval [10000, 99999] is 5514.
The count of colorful numbers within the interval [100000, 999999] is 13956.
The count of colorful numbers within the interval [1000000, 9999999] is 21596.
The largest possible colorful number is 98746253.
The total number of colorful numbers is 57256.
</pre>
 
=={{header|Wren}}==
Line 634 ⟶ 2,379:
{{libheader|Wren-math}}
{{libheader|Wren-set}}
{{libheader|Wren-seq}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "./math" for Int, Nums
import "./set" for Set
import "./seq" for Lst
import "./fmt" for Fmt
 
Line 695 ⟶ 2,438:
var cn = (0..99).where { |i| isColorful.call(i) }.toList
System.print("The %(cn.count) colorful numbers less than 100 are:")
for (chunk in Lst.chunks(cn, 10)) Fmt.printtprint("$2d", chunkcn, 10)
 
countColorful.call(0, "")
Line 704 ⟶ 2,447:
var pow = 10
for (dc in 1...count.count) {
Fmt.print(" $d digit colorful number count: $,6d - $7.3f\%", dc, count[dc], 10100 * count[dc] / pow)
pow = (pow == 10) ? 90 : pow * 10
}
 
Fmt.print("\nTotal colorful numbers: $,d", Nums.sum(count))</langsyntaxhighlight>
 
{{out}}
Line 738 ⟶ 2,481:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">func IPow(A, B); \A^B
int A, B, T, I;
[T:= 1;
Line 809 ⟶ 2,552:
IntOut(0, Total);
CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
1,978

edits