I've already tried writing the function but I think what I have is a load of garbage, so unless it'd be worthwhile I'm not going to post it.
Might be a good idea to post it then. If nothing else but give people a chance to let you know how to make it better.
Also It would make more sense to know what these variables are.
If there was something I would say about the code it would be make your variables descriptive. Variables like b, N & p do not tell you or anyone else about what they represent.
When you write large portions of code you won't know which way is up with variables like these.