Make internal loop something like
while (flag) {
// smaller step 1
if (!flag) break;
// so on
}
As a side-note, if your internal loop takes very long time, it may indicate you using some sub-optimal algorithm. Though, if you working with very large numbers, long calculation times are unavoidable.