He worked it out with a pencil.
He stuck the pencil up his anus in order to dislodge the feces that would not budge, in other words. I'm guessing he used the eraser end, as sticking yourself with the sharpened end could be quite painful. And then he threw the pencil away. Or perhaps he washed it off. Either way, it isn't important to the joke. Although I'm thinking he placed the fouled pencil in with the pencils of a rival mathematician. That would be an even funner joke.