Project Euler #10 Java solution not working

后端 未结 6 441
春和景丽
春和景丽 2020-12-12 00:01

I\'m trying to find the sum of the prime numbers < 2,000,000. This is my solution in Java but I can\'t seem get the correct answer. Please give some input on what could b

6条回答
  •  抹茶落季
    2020-12-12 00:21

    Here is my solution

      public class ProjectEuler {
    
        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;
            }
        }
    
    
        public static long sumOfAllPrime(int number){
            long sum = 2;
    
            for (int i = 3; i <= number; i += 2) {
                if (isPrime(i)) {
                    sum += i;
                }
            }
    
            return sum;
        }
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            System.out.println(sumOfAllPrime(2000000));
        }
    }
    

提交回复
热议问题