
/* Simplification of nested radicals.
*/

RadSimp(_n) <--
[
  Local(max);
  Set(max, MathCeil(N(n^2)));
  Set(result,0);
  Set(result,RadSimpTry(n,0,1,max));
  if (CheckRadicals(n,result))
    result
  else
    n;
];

/*Echo({"Try ",test}); */

CheckRadicals(_n,_test) <-- Abs(N(n-test,20)) < 0.000001;


RadSimpTry(_n,_result,_current,_max)<--
[
  if (LessThan(N(result-n), 0))
  [
    Local(i);
    For (Set(i,current),i<=max,Set(i,MathAdd(i,1)))
    [
      Local(new, test);
      Set(test,result+Sqrt(i));

/* Echo({"Cut-try ",test});  */


      if (CheckRadicals(n,test))
      [
        Set(result,test);
        Set(i,MathAdd(max,1));
      ];
    ];

    if (LessThan(N(result-n), 0))
    [
      For (Set(i,current),i<=max,Set(i,MathAdd(i,1)))
      [
        Local(new, test);
        Set(test,result+Sqrt(i));

/* Echo({"Full-try ",test}); */

        Set(new,RadSimpTry(n,test,i,max));
	if (CheckRadicals(n,new))
        [
          Set(result,new);
          Set(i,MathAdd(max,1));
        ];
      ];
    ];
  ];
  result;
];


