Skip to content

Instantly share code, notes, and snippets.

@Artoria2e5
Last active August 29, 2015 14:06
Show Gist options
  • Save Artoria2e5/3ba08c21be33ec56c6d8 to your computer and use it in GitHub Desktop.
Save Artoria2e5/3ba08c21be33ec56c6d8 to your computer and use it in GitHub Desktop.

Question 6

Cut numbers in {1..9} into 2 parts, and group them into two dec numbers, a and b, respectively. Given k∈{2..9}, and for different k, look for all possible pairs of a and b that meets the condition a*k == b

Solution

For every dec c, c*k can only be one digit longer or no longer than c. Since the toal length of a and b (in dec) has to be 9, we can get know that b has to be 5 digits long while a has to be 4 digits long. This makes the code a lot simpler.

For every k in {2..2..8}, we have b.lastDigit % 2 == 0. And for every k in {3..3..9}, we have b.allDigitSum % 3 == 0. Now we have the following code for listing everything we need.

Bash, as a language that writes as easily as pseudo-code:

# arrays a and b.
# just combines $*
decprint(){ for i; do printf $i; done; }
# Cuts the number into pieces so for..in works. The ${var:position:length} method is slow.
_break(){ for ((_b=0; b<${#1}; b++)); do printf "${1:_b:1} "; done; }
# cuts the dec
# returns an array, well it's stdout.
throw(){
  for _i in {1..9}; do
  _throw $* && printf "$_i "
  done 
}
_throw(){
  for _j; do
    [ "$_i" == "$_j" ] && return 1
  done; return 0
}
# Generate a
for a1 in {1..9}; do
a[1]=$a1
for a2 in $(throw $a1); do
a[2]=$a2
for a3 in $(throw $a1 $a2); do
a[3]=$a3
for a4 in $(throw $a1 $a2 $a3); do
a[4]=$a4; a=$(decprint ${a[@]}); echo $a
# test for k, potential b should have a length of 5.
for k in {2..9}; do
((b=a * k))
if [[ ${#b} == 5 ]]; then
# Duplicate use of $_i, in order to use _throw to search for duplicate numbers.
for _i in $(_break $b); do _throw ${a[@]} && echo "a=$a b=$b k=$k">&2; done
fi; unset b
done
done
done
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment