for (long long j = factored_num / 3; j > 2 || factored_num != 1; j -= 2) {
On a 64-bit computer, I’m trying to factor a number. This code works perfectly fine when long long j = factored_num, but when I do integer division, cout << j shows that j is negative — I’m assuming it overflows. How can I fix this?
I’ve tried 3LL, j-= 2LL, etc. in case it was a type problem. Again, it definitely has to do with the division part, but I’m not familiar enough with data types to immediately get the problem.
The problem could be the final condition. You loop while
jis more than 2 orfactored_numis not 1, so iffactored_numdoes not become one, the loop will not end and j will continue to decrement to negative numbers.I’d expect the condition to be
j > 2 && factored_num != 1, that is you want to end ifjis 2 or less (why 2; 2 is a valid factor) or factored_num is 1 (and therefore does not have any more factors).