Thuật toán kiểm tra số nguyên tố (Pascal, C++, Python, Scratch)
Viết chương trình kiểm tra một số n (n <2 tỉ) có phải là số nguyên tố hay không.
Dữ liệu vào file: nguyento.inp | Dữ liệu ra file: nguyento.out |
Chứa số n | Yes (No) |
Code kiểm tra số nguyên tố trong Pascal
program kiem_tra_nguyen_to; var m:longint;f:text; {------ chuong trinh con kiem tra so nguyen to ----} function ngto(n:longint):boolean; var i:longint; begin if n<2 then ngto:=false else ngto:=true; for i:=2 to trunc(sqrt(n)) do if n mod i = 0 then begin ngto:=false; break; {thoat vong lap} end; end; {--- het CT con------} {----Than chuong trinh chinh ------} begin {----Doc file ----} assign(f,'nguyento.inp'); reset(f); readln(f,m);close(f); {----Mo file de ghi----} assign(f,'nguyento.out'); rewrite(f); if ngto(m) then write(f,'yes') else write(f,'no'); close(f); end.
Code kiểm tra số nguyên tố trong Python
f = open("nguyento.inp") a = int(f.read()) f.close() snt = False for i in range (2,a): if a % i == 0: snt = True break fo = open("nguyento.out", "w") if a < 2: fo.write("No") else: if snt == True: fo.write("No") else: fo.write("Yes") fo.close()
Code kiểm tra số nguyên tố trong C
#include <stdio.h> #include <math.h> int main(){ int n; printf("\nNhap n = "); scanf("%d", &n); if(n < 2){ printf("\n%d khong phai so nguyen to", n); return 0; } int count = 0; for(int i = 2; i <= sqrt(n); i++){ if(n % i == 0){ count++; } } if(count == 0){ printf("\n%d la so nguyen to", n); }else{ printf("\n%d khong phai so nguyen to", n); } }
Code kiểm tra số nguyên tố trong C++
#include <iostream> #include <math.h> using namespace std; int main(){ int n; cout << "\nNhap n = "; cin >> n; if(n < 2){ cout << n << " khong phai so nguyen to\n"; return 0; } int count = 0; for(int i = 2; i <= sqrt(n); i++){ if(n % i == 0){ count++; } } if(count == 0){ cout << n << " la so nguyen to\n"; }else{ cout << n << " khong phai so nguyen to\n"; } }
Code kiểm tra số nguyên tố trong Scratch