Not sure if I'm right here, but this is my best solution.
First of all, in my solution:
The number of years doesn't seem to matter. I hope that doesn't mean my numbers are off!
So, with that, I came up with the following formula:
Ending balance = P * (1-(F/P))^TN * (1+R/T)^TN
Where
N = the number of years
P = Principle (1,001)
F = Fee ($1)
T = Transfers/year
R = interest Rate (0.1)
Since I wasn't able to think of a way to expand that formula to give me the Transfers/year rate that would give me the highest value for an ending balance, I brute forced it by trying numbers and came up with:
2.1703 transfers per year (or a total of 2.1703N withdrawals, rounded to the nearest whole number. If you need a whole number of times per year, then 2 is better than 3, or if you want it in days, It's every 168 days.
For 10 years, it's a total of 22 times. For 100, you'd want to transfer your money 217 times, every 168 or 169 days.
For your example of 40 years, you should do it every 167-168 days to total 87 transfers, ending with $45,824.26, a $5,824.26 gain over just leaving it alone.