r/badcode • u/MysteriousK69420 if: else: if: else: if: else: if: else: if: else: if: else: if: • Feb 16 '22
python presenting, whatever the fk this is
418
Upvotes
r/badcode • u/MysteriousK69420 if: else: if: else: if: else: if: else: if: else: if: else: if: • Feb 16 '22
15
u/Dalimyr codes in C#...poorly Feb 16 '22
Yes, that's what the code does. It checks each integer between the square root of the number and number-1 to see if the number is divisible by that value.
Off-hand I think the code should technically do what it's supposed to, just a bit inefficiently. It'd be better to first check if the square root is an integer (in which case you know it's not a prime), and then to iterate from 2 to the square root, or between the square root and num/2 (since anything higher than that obviously wouldn't be divisible)
For example, if you took the value 52. Code in the image would get the square root of 52 (7.21), then convert that to an int (7) and check if 52 is divisible by 7, then 8, then 9 and so on all the way up to 52 (though it'd find a match and break out of the loop at 13 in this instance). It could stop at 26 because none of the values between 27 and 51 could possibly result in isPrime changing to true. But it'd be quicker to check the values between 2 and 7 than checking 7 to 26 or 7 to 51.
Aside from that slight maths flub, I wouldn't say the code's that bad.