Competitive/Collaborative Programming Class

ICPC Computer Programming Contest Prep

Problem Solving in Computer Science

Spring 2013 -- CSC 2700 Section 02

[Isaac's Home Page ]  [Mailing List ]  [Class Page ]  [Normal ]  

week12/i/ConsecutiveSums.java

/*
 *  Author: Son Pham
 *    Date: April 20, 2013
 * Purpose: Solves this problem using the concept behind the
 *          maximum sum subarray problem.
 * Problem: 1210 - Sum of Consecutive Prime Numbers
 * Comment: Too easy. Isaac's sieve idea is genius.
 */

import java.util.*;

public class ConsecutiveSums {

    private static int[] numbers = new int[10001];
    private static int[] primes;

    public static void main(String[] args) {
        sievePrimes(numbers);
        Scanner reader = new Scanner(System.in);
        int n = reader.nextInt();
        while(n != 0){
            System.out.println(sumCount(n));
            n = reader.nextInt();
        }
    }

    public static int sumCount(int n){
        int count = 0;
        int j = primes.length - 1;
        int i = j;
        int sum = primes[j];
        while((i > -1) && (j > -1)){
            if(i > j){
                i = j;
                sum += primes[i];
            }
            if(sum > n){
                sum -= primes[j];
                j--;
            }
             else if(sum < n){
                i--;
                if(i > -1){
                    sum += primes[i];
                }
             }
             else if(sum == n){
                 count++;
                 sum -= primes[j];
                 j--;
             }
        }
        return count;
    }

    public static void sievePrimes(int[] p){
        p[0] = 1;
        p[1] = 1;
        for(int i =2; i < p.length; i++){
            if(p[i] != 1){
                int j = 2;
                int index = i*j;
                while(index <= 10000){
                    p[index] = 1;
                    j++;
                    index = i*j;
                }
            }
        }
        ArrayList<Integer> prime = new ArrayList();
        for(int i = 2; i < numbers.length; i++){
            if(p[i] == 0){
                //System.out.println(i);
                prime.add(i);
            }
        }
        primes = new int[prime.size()];
        for(int i = 0; i < primes.length; i++){
            primes[i] = prime.get(i);
        }
        //System.out.println(primes.length);
    }

}

The statements and opinions included in these pages are those of only. Any statements and opinions included in these pages are not those of Louisiana State University or the LSU Board of Supervisors.
© 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Isaac Traxler