One fairly simple method would be to query and ApexClass object and get the distinct NamespacePrefix values.
Select NamespacePrefix from ApexClass Group By NamespacePrefix
This assumes that every installed managed package has at least one ApexClass, which may not be the case. You could expand it to include the ApexPage and ApexTrigger sObjects. Again, the managed package doesn't have Visualforce pages or triggers this won't pickup the namespace either.
A more comprehensive option is to use the listMetadata call against the MetaData API. This can be a bit more fiddly to invoke from Apex.
Incidentally, the salesforce.stackexchange.com site is a great place to ask Salesforce specific questions.