• Home

  • Forum

  • Articles

  • About

    • Contact
  • Donate

  • More

    Use tab to navigate through the menu items.

    Buddha Institute of Technology

    lotus.png
    To see this working, head to your live site.
    • Categories
    • All Posts
    • My Posts
    Apsara Oum-Fite
    Aug 29, 2018

    Sum of Primes

    in Problem Sets

    A prime number is a number that cannot be divided by any number other than 1 and itself (ie. 2, 17, 53, etc.).


    Find the sum of all prime numbers from 0 to 7600 (2 + 3 + 5 + 7 + 11 + 13... = ?).

    1 comment
    0
    Apsara Oum-Fite
    Aug 30, 2018

    These are two possible solutions in Java.


     

    SOLUTION #1


    public static void main(String[] args) {

    int max = 7600, sum = 0;

    ArrayList<Integer> primes = new ArrayList<Integer>();

    for(int i = 2; i <= max; i++) {

    boolean prime = true;

    for(int j = 0; j < primes.size() && prime; j++) {

    if(i % primes.get(j) == 0)

    prime = false;

    if(primes.get(j) > i/2)

    j=primes.size();

    }

    if(prime) {

    primes.add(i);

    sum += i;

    }

    }

    System.out.println("Sum:\t" + sum);

    }


     

    SOLUTION #2


    public static ArrayList<Integer> primes = new ArrayList<Integer>();


    public static boolean isPrime(int k) {

    boolean prime = true;

    for(int idx = 0; idx < primes.size() && prime; idx++) {

    if(k % primes.get(idx) == 0)

    prime = false;

    if(primes.get(idx) > k/2)

    idx = primes.size();

    }

    if(prime) primes.add(k);

    return prime;

    }

    public static void main(String[] args) {

    int max = 7600, sum = 0;

    for(int i = 2; i <= max; i++) {

    if(isPrime(i))

    sum += i;

    }

    System.out.println("Sum:\t" + sum);

    }


     

    0
    1 comments

    © 2018 by Apsara Oum-Fite