Wrong code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public class SumOfPrimes {
    public static void main(String[] args) {
        long sum = 0;
        for (int i = 2; i <= 1000; i++) {
            if (isPrime(i)) {
                sum += i;
            }
        }
        System.out.println(sum);
    }

    private static boolean isPrime(final int number) {
        for (int i = 2; i * i <= number; i++) {
            if (number % i == 0) {
                return false;
            }
        }
        return true;
    }
}  

Above shows a java program. What is the positive integer output?


The answer is 76127.

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

2 solutions

Saksham Jain
Nov 18, 2017

I ran it in AIDE

Hasmik Garyaka
Oct 6, 2017

I run it in NetBeans

This is the wrong code to determine the sum of all prime numbers 1-1000. Do you know the correct code?

Munem Shahriar - 3 years, 8 months ago

Log in to reply

It is not wrong, but not optimal. Optimal would be eratosphene siege.

Hasmik Garyaka - 3 years, 8 months ago

Log in to reply

So do you mean sum of all prime numbers 1-1000 is 76127?

Munem Shahriar - 3 years, 8 months ago

Log in to reply

@Munem Shahriar It's not the first such question in community. I have this program.

Hasmik Garyaka - 3 years, 8 months ago

@Munem Sahariar I also think this is wrong code.To get correct output do not use i*I there instead use i

Saksham Jain - 3 years, 6 months ago

import java.util.Arrays;

int n; boolean[] primes = new boolean[n + 1];

public void fillSieve() { Arrays.fill(primes, true); primes[0] = primes[1] = false; for (int i = 2; i < primes.length; ++i) { if (primes[i]) { for (int j = 2; i * j < primes.length; ++j) { primes[i * j] = false; } } } }

Hasmik Garyaka - 3 years, 8 months ago

Log in to reply

Where should I run this code? It doesn't work here

Munem Shahriar - 3 years, 8 months ago

Log in to reply

In some IDE

Hasmik Garyaka - 3 years, 8 months ago

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...