The drug Truvada, made by Gilead, was approved seven years ago for PrEP. Taken daily, it appears to be almost completely effective in protecting users against H.I.V. infection.

But just 35 percent of the 1.1 million people who could benefit from the pills use them. And there are nearly 40,000 new H.I.V. infections a year in the United States.

The problem is especially acute among black gay and bisexual men: one in two will be infected with H.I.V. in his lifetime, said Julia Marcus, a public health researcher at Harvard Medical School and a developer of the new algorithm.

Use of PrEP has lagged for a number of reasons. Until recently, insurers did not always pay for the pills, which have a list price of about $2,100 a month. And patients do not always have a regular doctor who knows them well enough to discuss H.I.V. risk.

For the most part, the onus has been on patients to ask for PrEP, said Dr. Douglas Krakower, leader of the Harvard group developing an algorithm. “Clinicians are very busy and have limited time and tools to identify people who may be at risk,” he said.

Software might spare them the effort. “We intuitively felt like there were many data elements in the electronic health record that could predict risk,” said Dr. Marcus. The challenge was to identify which ones worked best.

So the groups developed several different models, using electronic records from 3.7 million uninfected patients at Kaiser Permanente and 1.1 million patients at two Massachusetts medical centers.