Saudi Arabia helped to save hundreds of lives in the UK by offering counter-terrorism intelligence, David Cameron has claimed.
The prime minister said it was important to keep close ties with the kingdom despite its poor human rights record.
Speaking at a Q&A hosted by Sky News, he also defended the government's decision to fly the Union flag at half-mast on public buildings as "a mark of respect" following the death of King Abdullah bin Abdulaziz in January.
Cameron said: "I can tell you one time since I've been prime minister, a piece of information that we have been given by that country has saved potentially hundreds of lives here in Britain.
"Now, you can be prime minister and say exactly what you think about every regime in the world and make great headlines, and give great speeches.
"But I think my first job is to try and keep this country safe from terrorism and if that means you have to build strong relationships sometimes with regimes you don't always agree with, that I think is part of the job and that is the way I do it. And that is the best way I can explain it."
The case of Saudi Arabian activist Raif Badawi who was sentenced to 1,000 lashes and 10 years in prison for insulting Islam also was discussed.
"It's perfectly possible to go to those countries as I do and raise human rights abuses," Cameron said.
"I would argue that if you have a relationship with them and you have a way of talking to them they are more likely to listen to you than if you just cut yourself off."
He agreed close ties with the Arab kingdom were linked to the fact it had wide oil resources.
Cameron said: "Of course Britain needs to have relationships with countries we trade with, including those that we buy oil and gas from.
"We can't make all our oil and gas here in the UK, we're doing well because we've got North Sea oil."