Your code does NOT work well. In fact, it has a serious bug in it.
You are using a loop. EVERY pass through the loop, it sets y2 to be either true or false. So if the final pass through the loop, you just happen to get the result that mod(x2,i) == 0 or not, then your code will fail.
Instead, if ANY of those mods is zero, then you are done. There is no need to test any further, as the number cannot be prime. So you can use break to exit the loop as soon as that happens. Or you can use a while loop.
Next, you should recognize that going all the way out to x2/2 is far too long of a loop. Do you need to go past sqrt(x2)? THINK ABOUT IT!
Consider the difference between
Which loop do you want to execute?