fork download
  1. #include <stdio.h>
  2. #include <stdbool.h>
  3. #include <math.h>
  4.  
  5. int power(int a, int b, int c) {
  6. int result = 1;
  7. while (b > 0) {
  8. if (b % 2 == 1)
  9. result = (result * a) % c;
  10. b /= 2;
  11. a = (a * a) % c;
  12. }
  13.  
  14. return result;
  15. }
  16.  
  17. bool is_prime(int n) {
  18. if (n < 2)
  19. return false;
  20. if(n == 2)
  21. return true;
  22.  
  23. for (int k = 2; k <= sqrt(n); k++) {
  24. if (n % k == 0)
  25. return false;
  26. }
  27.  
  28. int a = 2;
  29. if (power(a, n-1, n) != 1)
  30. return false;
  31.  
  32. return true;
  33. }
  34.  
  35. int main() {
  36. int n;
  37. printf("Nhap mot so nguyen duong: ");
  38. scanf("%d", &n);
  39.  
  40. if (is_prime(n))
  41. printf("%d la so nguyen to.\n", n);
  42. else
  43. printf("%d la hop so.\n", n);
  44.  
  45. return 0;
  46. }
  47.  
Success #stdin #stdout 0s 5444KB
stdin
Standard input is empty
stdout
Nhap mot so nguyen duong: 32766 la hop so.