Determining if a number is prime

后端 未结 20 1367
悲哀的现实
悲哀的现实 2020-11-30 03:05

I have perused a lot of code on this topic, but most of them produce the numbers that are prime all the way up to the input number. However, I need code which only checks w

20条回答
  •  误落风尘
    2020-11-30 03:33

    I follow same algorithm but different implementation that loop to sqrt(n) with step 2 only odd numbers because I check that if it is divisible by 2 or 2*k it is false. Here is my code

    public class PrimeTest {
    
        public static boolean isPrime(int i) {
            if (i < 2) {
                return false;
            } else if (i % 2 == 0 && i != 2) {
                return false;
            } else {
                for (int j = 3; j <= Math.sqrt(i); j = j + 2) {
                    if (i % j == 0) {
                        return false;
                    }
                }
                return true;
            }
        }
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            for (int i = 1; i < 100; i++) {
                if (isPrime(i)) {
                    System.out.println(i);
                }
            }
        }
    
    }
    

提交回复
热议问题