While I'm not aware of the specific formula for this, I know a bit of the history. In Bitcoin the difficulty is adjusted every 2016 blocks based on the average hashrate over that period. The difficulty is calculated so that the average block time should be 10 minutes. Megacoin improved on this by recalculating the difficulty based on a moving average of previous blocks, this was called the Kimoto Gravity Well. This provided some robustness in the face of rapidly changing price and hashrate, which has been a particular problem for recent forks of Bitcoin like Bitcoin Cash. Dash has further improved on the Kimoto Gravity Well to remove a time-warping exploit, and the result was named Dark Gravity Wave. There's a bit of info on the wiki about this, but I'd be interested in how this is calculated as well...