Problem 50. Consecutive prime sum

Description

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class euler50 {
    public static void main(String[] args) {
        Map<Integer, Integer> m = new HashMap<Integer, Integer>();
        int prime = 0;
        int k = 0, l = 1;
        int sum = 0;
        int maxSum = 0;
        int sumPrime = 0, sumFinal = 0;
        int max = 0;
        int count = 0;
        boolean found = false;
        while (l < 1000) {
            k = l;
            while (sumPrime < 1000) {
             	sumFinal = sumPrime;
             	found = false;
              	k++;
                if (isPrime(k)) {
                    prime = k;
                    found = true;
                    System.out.println("Prime: " + prime);
                }
                if (found) {
                    sum += prime;
                    count++;
                    if (isPrime(sum)) {
                        sumPrime = sum;
                        if (sumPrime < 1000)
                             m.put(count, sumPrime);
                    }
                }
            }
            count = 0;
            sumFinal = 0;
            sumPrime = 0;
            sum = sumPrime;
            l++;
        }
        Set s = m.entrySet();
        Iterator it = s.iterator();
        while (it.hasNext()) {
            Map.Entry map = (Map.Entry)it.next();
            int key = (Integer)map.getKey();
            if (key > max) {
                max = key;
               	maxSum = (Integer)map.getValue();
            }
       	}
        System.out.println("Final: " + maxSum + " " + max);
    } 
    public static boolean isPrime(int n) {
        if (n > 1) {
            int i = n-1;
            while (i > 1) {
                if (n % i == 0)
                    return false;
                i--;
            }
            if (i == 1)
                return true;
            else
             	return false;
       	}
       	else
           return false;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>