Có tính chất: chỉ những số có tổng các chữ số chia hết cho 3 thì nó mới chia hết cho 3 và ngược lại. Nên mình làm 2 bản:
Bản 1: Đầy đủ theo đề:
uses crt;
var x,y,i,d:longint;
function nt(a:longint):boolean;
var i:longint;
begin
i:=2;
while(a>1)and(a mod i<>0)do inc(i);
nt:=i=a;
end;
function tong(a:longint):longint;
begin
tong:=0;
repeat
inc(tong,a mod 10);
a:=a div 10;
until a=0;
end;
begin
clrscr;
write('Nhap x,y: ');readln(x,y);
for i:=x to y do
if (nt(i))and(tong(i) mod 3=0) then
inc(d);
writeln('Ket qua: ',d);
readln
end.
Bản 2: Không cần tính tổng (rút gọn theo tính chất):
uses crt;
var x,y,i,d:longint;
function nt(a:longint):boolean;
var i:longint;
begin
i:=2;
while(a>1)and(a mod i<>0)do inc(i);
nt:=i=a;
end;
begin
clrscr;
write('Nhap x,y: ');readln(x,y);
for i:=x to y do
if (nt(i))and(i mod 3=0) then
inc(d);
writeln('Ket qua: ',d);
readln
end.