Advertisement
Paul_Pedant

Ramanujan Bash (using sparse array).

May 20th, 2020
396
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 0.87 KB | None | 0 0
  1. #! /bin/bash
  2.  
  3. Ways=1
  4.  
  5. [[ "${1}" == -[1-9] ]] && { Ways=$(( 0 - ${1} )); shift; }
  6.  
  7. Max="${1:-100000}"
  8. Root=0
  9.  
  10.     for (( Root = 1; (Root * Root * Root) <= Max; ++Root )); do : ; done
  11.     Root=$(( Root - 1 ))
  12.  
  13.     printf 'Ways is %d; Max is %d; Root is %d\n' "${Ways}" "${Max}" "${Root}"
  14.  
  15.     for (( a = 1; a <= Root; ++a )); do
  16.         for (( b = a; b <= Root; ++b )); do
  17.             v=$(( a * a * a + b * b * b ))
  18.             (( v <= Max )) &&
  19.                 printf -v N[v] '%s %d,%d' "${N[${v}]}" "${a}" "${b}"
  20.         done
  21.     done
  22.  
  23.     r="${#N[@]}"
  24.  
  25.     (( Ways > 1 )) && for n in ${!N[@]}; do
  26.         read -a Fact <<<"${N[${n}]}"
  27.         (( ${#Fact[@]} < Ways )) && unset N[${n}]
  28.     done
  29.  
  30.     printf 'Showing %d %d-way of %d results.\n' "${#N[@]}" "${Ways}" "${r}"
  31.  
  32.     for n in ${!N[@]}; do
  33.         printf '%8d  %s\n' "${n}" "${N[${n}]}"
  34.     done
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement