The worst-case runtime of this algorithm is O(n). Your algorithm works by counting up from 2 up to n (so the loop runs O(n) times) and, at each step, doing some arithmetic operations (each of which runs in time O(1)). Therefore, the overall runtime is O(n).
You can speed this up in a few ways. One way is to only count up to √n rather than n itself, since if n has any divisors at all, at least one of those divisors is a prime number. There's a cool fact that any prime divisor of a number n has to be no greater than √n, so you only need to count up to √n, inclusive. That drops your runtime to O(√n), which is a noticeable improvement.
There are other algorithms you can use to speed this up further, but they're quite complicated and only really useful for very, very large integers.
You've asked about getting this down to time O(1). Since there are only finitely many possible values that can fit into an int
, one option would be to build a giant table of all the prime numbers that fit into an int
, store them in a hash table, and then look up the number in question in that table. It's not elegant and its a huge memory hog, but it will work.
Depending on your use case, you might also want to check out the Sieve of Eratosthenes, which will give you a way of computing all the prime numbers up to some number n in time O(n), afterwards giving O(1) queries for any number in that range.
Hope this helps!