fork download
  1.  
  2. //B-prime
  3.  
  4. #include <iostream>
  5.  
  6. using namespace std;
  7.  
  8. bool isPrime(int n) {
  9.  
  10. if (n < 2) {
  11.  
  12. return false;}
  13.  
  14. for (int i = 2; i * i <= n; ++i) {
  15.  
  16. if (n % i == 0) {
  17.  
  18. return false;}}
  19.  
  20. return true;}
  21.  
  22. int findYForPrime(int x) {
  23.  
  24. if (x == 2 || x == 3) {
  25.  
  26. return -1; // No valid "y" for 2 or 3
  27. }
  28. if (!isPrime(x)) { return -1; // Not prime number
  29. }
  30. if (x % 6 == 1) {
  31.  
  32. return (x - 1) / 6;
  33.  
  34. } else if (x % 6 == 5) {
  35.  
  36. return (x + 1) / 6;
  37.  
  38. } else {
  39.  
  40. return -1; // Invalid prime number (not of the form 6y ± 1)
  41. }}
  42. int main() {
  43.  
  44. int prime;
  45. cout << "Enter your number: ";
  46.  
  47. cin >> prime;
  48.  
  49. int yValue = findYForPrime(prime);
  50.  
  51. if (yValue != -1) {
  52.  
  53. cout << "For prime " << prime << ", y = " << yValue << endl;
  54.  
  55. }
  56. else {
  57.  
  58. cout << "Not a prime number: " << prime << endl;
  59. }
  60. return 0;
  61. }
  62.  
Success #stdin #stdout 0.01s 5304KB
stdin
5 9
stdout
Enter your number: For prime 5, y = 1