LONDON — Counterterrorism officers thwarted a terrorist attack targeting the British prime minister, Theresa May, prosecutors said when two suspects in their early 20s appeared in court on Wednesday.

Word of the planned attack coincided with what the authorities have depicted as mounting concern about the intensity, scale and pace of conspiracies by violent extremists.

There have been five terrorist attacks in Britain this year alone, killing dozens of people in total. An official report on Tuesday said the worst of those assaults — at a concert by the pop star Ariana Grande in Manchester in May — might have been averted “had the cards fallen differently.”

The planned attack on Mrs. May was to begin with a bombing of the security gates that protect 10 Downing Street — the home and office of British prime ministers — as a prelude to an attempt to stab her to death, prosecutors said.