2-prime

(Time: 1 sec. Memory: 16 MB Difficulty: 28%) A number is called 2-simple if the primes are composed of digits of this number in ascending and descending order.

It is required to write a program that, by a given number, determines its 2-simplicity.

Input data
The input file INPUT.TXT contains a positive integer N (10 <N <10 9 ).

Output
In the output file OUTPUT.TXT output the message "Yes" if the number N is 2-simple and "No" - otherwise.

Here is my code:

  #include <iostream> #include <string> #include <stdlib.h> using namespace std; int i ,x,k, sum , n, re; int main() { cin >> n; if (n < 10) { re += 1; } for (int i = 2; i < n - 1; i++) { if (n%i == 0) { re += 1; } } string s = to_string(n); reverse(s.begin(), s.end()); sum = atoi(s.c_str()); for (int i = 2; i < sum - 1; i++) { if (sum % i == 0) { re += 1; } } if (re == 0) { cout << "Yes"; } else { cout << "No"; } return 0; } 

Writes what's wrong. Where is the mistake?

  • one
    At least, without delving into the logic, your re variable is not initialized before use. - Yaant
  • one
    @Yaant: The variable re declared at the namespace level, which means that it is implicitly initialized to zero. - AnT 7:05 pm
  • @AnT Ah, there it is. I'll know. :) - Yaant 7:07 pm
  • No, you think wrong. This is C ++. He defined the address for the variable, that's all. The value no one asked to change. There is rubbish in it - Egor Randomize

1 answer 1

Your approach is wrong.

The first is that you simply reverse the order of the digits of the number, but you need to get from your number 2 others - well, if you have 173645, then these are 134567 and 765431 (" numbers composed of digits of this number in ascending and descending orders ").

Secondly, performing a full cycle when checking for simplicity, you will definitely fly out of the allotted time. It suffices to check for divisibility to the square root of n ...

If you want to work through a string, then you can get two necessary numbers

 string s = to_string(n); sort(s.begin(), s.end()); int n1 = stoi(s); reverse(s.begin(), s.end()); int n2 = stoi(s); 

Well, I would do a check for simplicity like this.

 bool isPrime(int n) { if (n%2 == 0) return false; for(int i = 3; i*i <= n; i+=2) if (n%i==0) return false; return true; } 
  • Once again, I suggest minusator :) to explain what I am wrong. - Harry
  • there plus and not minus - AR Hovsepyan
  • @ARHovsepyan Two plus and one negative. If you click on a number, it shows how much of both. - HolyBlackCat
  • @HolyBlackCat, hmmm! .. thanks, I didn't even know ... - AR Hovsepyan
  • @Harry, is it still not better to determine the simplicity of the number in the compile time? .. - AR Hovsepyan