2
$\begingroup$

I need to write a program that uses an alternate algorithm when the algorithm first attempted is taking too long. Here is a minimal example.

foo[n_Integer]:=CheckAbort[TimeConstrained[soln=FactorInteger[n],3],{{n,1}}];
foo[140]
(* {{2,2},{5,1},{7,1}} *)

The example above did what I expected. However, in the next example FactorInteger requires more than three seconds. In that case I wanted foo to return {{n,1}} where (n=10^100+3). Instead I get $Aborted.

foo[10^100+3]
(* $Aborted *)

How do I get foo to do what I wanted.

$\endgroup$

1 Answer 1

3
$\begingroup$

If I understand what you're trying to do, you can just use TimeConstrained on its own:

foo[n_Integer] := TimeConstrained[FactorInteger[n], 3, {{n, 1}}]
$\endgroup$
1
  • $\begingroup$ Strange it works on this problem. When I tried this on a complicated application the kernel stops when the time-constraint is exceeded. $\endgroup$
    – Ted Ersek
    Mar 21, 2022 at 22:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.