Pascal | Viết hàm kiểm tra số N có phải là số nguyên tố hay không?

Pascal | Viết hàm kiểm tra số N có phải là số nguyên tố hay không?

Viết hàm kiểm tra số N có phải là số nguyên tố hay không?

Hướng dẫn: Khai báo hàm kiểm tra số nguyên tố có:

Tên hàm: KiemtraSNT

Dữ liệu trả về: int, ( 0 nếu không phải là số nguyên tố, là 1 nếu là số nguyên tố )

Tham số: tham trị là int N, số cần kiểm tra.

Xử lý kiểm tra: Dựa trên ví dụ đã có ở phần trước.

Nội dung hàm:

Function  KiemtraSNT(  N : Integer ) : Boolean;

Var flag : Boolean;

       i : Integer;

Begin

    flag := True;                                    { Khoi gan gia tri dung cho ktrSNT}

    For  i := 2 to  N-1 do           { Lap voi moi i co gia tri tu 2 den N-1}

            If ( N mod i = 0 ) then                        { Kiem tra xem N co’ chia het cho i hay khong}

                    flag:=false;                      { Neu dung thi khong con la so nguyen to nua}

    KiemtraSNT:=flag;

End;

Cải tiến, không sử dụng biến phụ:

Function KiemtraSN(  N : Integer ) : Integer;

Var i :integer;

Begin

    For  i := 2 to  N-1 do           { Lap voi moi i co gia tri tu 2 den N-1}

            If ( N mod i = 0 ) then                        { Kiem tra xem N co’ chia het cho i hay khong}

                    Writeln('N khongla SNT')      { Neu dung thi khong con la so nguyen to nua}

            Else

                    Writeln('N la SNT');        { N la SNT}

End;
Bạn thấy bài viết này như thế nào?: 
Average: 4.5 (83 votes)
Ảnh của Tommy Tran

Tommy owner Express Magazine

Drupal Developer having 9+ year experience, implementation and having strong knowledge of technical specifications, workflow development. Ability to perform effectively and efficiently in team and individually. Always enthusiastic and interseted to study new technologies

  • Skype ID: tthanhthuy

Advertisement

 

jobsora

Dich vu khu trung tphcm

Dich vu diet chuot tphcm

Dich vu diet con trung

Quảng Cáo Bài Viết

 
Sử dụng CasperJS, Drush and Jenkins để test Drupal

Sử dụng CasperJS, Drush and Jenkins để test Drupal

A few weeks ago, spurred on by some frustrating interactions with Behat and Javascript, I started looking into alternative frameworks for running behavioral tests against Drupal

Hướng dẫn xóa Content Types và Fields trong Drupal

Hướng dẫn xóa Content Types và Fields trong Drupal

The short answer to this question is, the nodes remain in the database. You can see the nodes listed in the Find Content admin page.

Drupal 7

Tổ chức modules directory trong Drupal

Ever feel like your Drupal code is becoming a disorganised mess? Most Drupal sites contain a decent number of contributed modules

Công ty diệt chuột T&C

 

Diet con trung