Depends what you want really. Personally I believe the K100d offers "more camera" for the money. The only weakness is it has a small buffer, so if you wanted to shoot continuously until the card is full then the D40 would be better. That doesn't matter to me, it may to you.
People will be quick to point out that a camera is only part of a system, including lenses, flashes etc. The range of Nikon and Nikon-compatible lenses is larger, and more widely available - if you suddenly decide you need a certain lens you will usually be able to wander into a shop and buy one for Nikon, whereas an equivalent for Pentax may require ordering and in some cases a wait. This depends on whereabouts in the world you are. But actually if you want anything from the current range of "DA" lenses designed for the digital sensor, there should really be no problem getting lenses. Also if you start worrying about lens availability, remember that the K100d will work with any Pentax lens, the D40 will have no or limited functionality (e.g. no autofocus) with several Nikon lenses. As for flash, Nikon's flash system is generally considered the best, though Pentax's is effective.
In terms of image quality (assuming comparable lenses) I expect there would be no difference at all between the two... both use the same sensor and by now both companies have probably worked out how to get the best out of it.
There's no right or wrong, it depends on your priorities and preferences. Best advice I can give is to consider exactly what you're looking for in a camera and in a system, consider which would fit your needs best... oh and go to a shop and play with them both!