SPOJ Prime Generator Solution in Java


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class Main {

    public static void main(String[] args) {
        InputReader in = new InputReader(System.in);
        SieveOfEratosthenes soe = new SieveOfEratosthenes(SieveOfEratosthenes.LIMIT);

        int T = in.nextInt();
        while (T-- != 0) {
            int m = in.nextInt();
            int n = in.nextInt();
            if (n < SieveOfEratosthenes.LIMIT) {
                for (int i = m; i <= n; i++) {
                    if (soe.isPrime(i)) {
                        System.out.println(i);
                    }
                }
            } else {

                // primes which are lesser than the square root of n, since the
                // max prime factor of n will be less than or equal to square root of n
                List<Integer> primes = soe.getPrimes((int) Math.sqrt(n));

                boolean[] a = new boolean[n - m + 1];
                for (int i = 0; i < a.length; i++) {
                    a[i] = true;
                }

                // Similar to sieve of eratosthenes, fill the boolean
                // array with the divisibility with prime factors
                for (int prime : primes) {
                    int div = m / prime;
                    if (div * prime == m) {
                        a[0] = false;
                    } else {
                        div += 1;
                    }
                    for (int i = div * prime; i <= n; i += prime) {
                        if (i >= m && i <= n) {
                            a[i - m] = false;
                        }

                    }
                }

                for (int i = 0; i < a.length; i++) {
                    if (a[i]) {
                        System.out.println(m + i);
                    }
                }
            }
            System.out.println();
        }
    }

    public static class SieveOfEratosthenes {

        public static final int LIMIT = 10000000;

        private boolean[] a;

        public SieveOfEratosthenes(int N) {
            a = new boolean[N + 1];
            for (int i = 0; i < N; i++) {
                a[i] = true;
            }
            a[0] = false;
            a[1] = false;

            int root = (int) Math.sqrt(N);
            for (int i = 2; i <= root; i++) {
                for (int j = 2 * i; j <= N; j += i) {
                    a[j] = false;
                }
            }
        }

        public boolean isPrime(int n) {
            return a[n];
        }

        public List<Integer> getPrimes() {
            List<Integer> list = new ArrayList<Integer>();
            for (int i = 1; i < a.length; i++) {
                if (a[i]) {
                    list.add(i);
                }
            }
            return list;
        }

        public List<Integer> getPrimes(int n) {
            List<Integer> list = new ArrayList<Integer>();
            for (int i = 1; i <= n; i++) {
                if (a[i]) {
                    list.add(i);
                }
            }
            return list;
        }
    }

    public static class InputReader {
        private BufferedReader reader;
        private StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream));
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public long nextLong() {
            return Long.parseLong(next());
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }
    }
}

Sample Input:

2
1 10
3 5

Sample Output:

2
3
5
7

3
5

Segment Tree Implementation in Java

Segment tree is just another binary tree which supporting operations such as finding the minimum, maximum or sum of a given range of index in the array. The tree implementation is similar to the binary tree implementation of heap over an array.

Based on the requirements the current code for range minimum query can be modified for the range maximum query or range sum query.

The api for the given class looks like:

public class SegmentTree {
    public SegmentTree(int[] A);
    public int query(Point interval);
    public void update(int index, int value);
}

Complete Code:


import java.awt.*;

/**
 * Created by dhruv.pancholi on 17/01/16.
 * @author Dhruv Pancholi
 * @version 1.0
 */
public class SegmentTree {

    private int[] oArray;
    private int[] stArray;

    /**
     * Class which builds segment tree for the input array
     *
     * @param oArray original array
     */
    public SegmentTree(int[] oArray) {
        this.oArray = oArray;

        // The required length of the segment tree array
        // same as heap array
        int len = (int) Math.pow(2, Math.ceil(log2(oArray.length) + 1));
        stArray = new int[len];

        buildSegmentTree(0, new Point(0, oArray.length - 1));
    }

    /**
     * Builds a segment tree object for Range minimum query
     * Runtime: O(N*logN)
     *
     * @param node     index of the stArray which represents an interval
     * @param interval the interval which is represented by the node
     */
    private void buildSegmentTree(int node, Point interval) {
        if (interval.x == interval.y) {
            stArray[node] = interval.x;
            return;
        }
        Point children = new Point(2 * node + 1, 2 * node + 2);
        buildSegmentTree(children.x, new Point(interval.x, (interval.x + interval.y) / 2));
        buildSegmentTree(children.y, new Point((interval.x + interval.y) / 2 + 1, interval.y));
        stArray[node] = (oArray[stArray[children.x]] &lt;= oArray[stArray[children.y]]) ? stArray[children.x] : stArray[children.y];
    }

    /**
     * Update the value of the array and the corresponding tree
     *
     * @param node      Traversal node index
     * @param cInterval Interval in which the index lies
     * @param index     The index value to be updated
     * @param value     The value with which to be updated
     */
    private void update(int node, Point cInterval, int index, int value) {
        if (cInterval.x == cInterval.y) {
            oArray[index] = value;
            return;
        }

        if (index &lt;= (cInterval.x + cInterval.y) / 2) {
            update(2 * node + 1, new Point(cInterval.x, (cInterval.x + cInterval.y) / 2), index, value);
        } else {
            update(2 * node + 2, new Point((cInterval.x + cInterval.y) / 2 + 1, cInterval.y), index, value);
        }
        stArray[node] = (oArray[stArray[2 * node + 1]] &lt;= oArray[stArray[2 * node + 2]]) ? stArray[2 * node + 1] : stArray[2 * node + 2];
    }

    /**
     * Wrapper method for update
     * Update API
     * Runtime: O(lgN)
     * @param index Index to be updated
     * @param value The value to be updated with
     */
    public void update(int index, int value) {
        update(0, new Point(0, oArray.length - 1), index, value);
    }

    /**
     * @param node Parent of the given sub-segment tree
     * @param cInterval Current interval
     * @param rInterval Required interval
     * @return index of the minimum element in the given range
     */
    private int query(int node, Point cInterval, Point rInterval) {
        if (cInterval.y &lt; rInterval.x || cInterval.x &gt; rInterval.y) {
            return -1;
        }
        if (cInterval.x &gt;= rInterval.x &amp;&amp; cInterval.y &lt;= rInterval.y) {
            return stArray[node];
        }

        Point children = new Point(2 * node + 1, 2 * node + 2);
        Point result = new Point();
        result.x = query(children.x, new Point(cInterval.x, (cInterval.x + cInterval.y) / 2), rInterval);
        result.y = query(children.y, new Point((cInterval.x + cInterval.y) / 2 + 1, cInterval.y), rInterval);

        if (result.x == -1) {
            return result.y;
        }
        if (result.y == -1) {
            return result.x;
        }

        return (result.x &lt;= result.y) ? result.x : result.y;
    }

    /**
     * Wrapper method to query from outside
     * Runtime: O(lgN)
     *
     * @param rInterval interval in which minimum is required
     * @return range minimum index
     */
    public int query(Point rInterval) {
        return query(0, new Point(0, oArray.length - 1), rInterval);
    }

    /**
     * Default is to the base e
     *
     * @param x
     * @return log to the base 2
     */
    private double log2(int x) {
        return Math.log(x) / Math.log(2);
    }

    public static void main(String[] args) {
        int[] A = new int[]{8, 7, 3, 9, 5, 1, 10};
        SegmentTree segmentTree = new SegmentTree(A);
        segmentTree.update(6, -1);
        System.out.println(segmentTree.query(new Point(0, 6)));
    }
}

UVa 10082 WERTYU Solution in C++

Things to learn:

  • Usage of map STL

Complete Code:

#include <cstdio>
#include<map>
using namespace std;

int main() {
	char c;
	map<char, char> t;
	t[' '] =	' ';
	t['\n'] =	'\n';
	t['1'] =	'`';
	t['2'] =	'1';
	t['3'] =	'2';
	t['4'] =	'3';
	t['5'] =	'4';
	t['6'] =	'5';
	t['7'] =	'6';
	t['8'] =	'7';
	t['9'] =	'8';
	t['0'] =	'9';
	t['-'] =	'0';
	t['='] =	'-';
	t['W'] =	'Q';
	t['E'] =	'W';
	t['R'] =	'E';
	t['T'] =	'R';
	t['Y'] =	'T';
	t['U'] =	'Y';
	t['I'] =	'U';
	t['O'] =	'I';
	t['P'] =	'O';
	t['['] =	'P';
	t[']'] =	'[';
	t['\\'] =	']';
	t['S'] =	'A';
	t['D'] =	'S';
	t['F'] =	'D';
	t['G'] =	'F';
	t['H'] =	'G';
	t['J'] =	'H';
	t['K'] =	'J';
	t['L'] =	'K';
	t[';'] =	'L';
	t['\''] =	';';
	t['X'] =	'Z';
	t['C'] =	'X';
	t['V'] =	'C';
	t['B'] =	'V';
	t['N'] =	'B';
	t['M'] =	'N';
	t[','] =	'M';
	t['.'] =	',';
	t['/'] =	'.';
	while ((c=getchar()) != EOF) {
		putchar(t[c]);
	}
	return 0;
}

Sample Input:

O S, GOMR YPFSU/

Sample Output:

I AM FINE TODAY.

Runtime: 0.019s

UVa 837 Light and Transparencies Solution in C++

Things to learn:

  • Way of thinking 🙂

Complete Code:

#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>

using namespace std;

struct segment{
	double r, x1, x2, y1, y2;
};

bool segmentcomparator(const segment& a, const segment& b){
	return a.x1 < b.x1;
}

int main(){
	int n, nl, counter;
	segment tmp;
	vector<segment> v;
	vector<double> x;
	scanf("%d", &n);
	while(n--){
		v.clear(); x.clear();
		scanf("%d", &nl);
		while(nl--){
			scanf("%lf %lf %lf %lf %lf", 
				&tmp.x1, &tmp.y1, &tmp.x2, &tmp.y2, &tmp.r);
			x.push_back(tmp.x1);
			x.push_back(tmp.x2);
			if(tmp.x1>tmp.x2){
				swap(tmp.x1, tmp.x2);
				swap(tmp.y1, tmp.y2);
			}
			v.push_back(tmp);
		}
		sort(x.begin(), x.end());
		sort(v.begin(), v.end(), segmentcomparator);
		printf("%d\n", x.size()+1);
		for(int i=0; i<x.size(); i++){
			if(i==0){
				printf("-inf %.3f 1.000\n", x[i]);
				continue;
			}
			double result = 1.0;
			for(int j = 0; j<v.size(); j++){
				if(v[j].x1 <= x[i-1] && v[j].x2 >= x[i])
					result *= v[j].r;
			}
			printf("%.3f %.3f %.3f\n", x[i-1], x[i], result);
			if (i == x.size()-1) {
				printf("%.3f +inf 1.000\n", x[i]);
			}
		}
		if(n!=0) printf("\n");
	}
	return 0;
}

Sample Input:

1

3
2.0 2.0 9.0 2.0 0.9
13.5 2.0 4.0 8.5 0.7
17.0 10.0 7.0 8.5 0.8

Sample Output:

7
-inf 2.000 1.000
2.000 4.000 0.900
4.000 7.000 0.630
7.000 9.000 0.504
9.000 13.500 0.560
13.500 17.000 0.800
17.000 +inf 1.000

Time Taken: 0.009s

UVa 739 Soundex Indexing Solution in C++

Things to learn:

  • I/O in C++
  • C Strings

Complete Code:

#include<cstdio>
#include<cstring>

int soundexcode (char x)
{
    char array0 [] = "AEIOUYWH";
    char array1 [] = "BPFV";
    char array2 [] = "CSKGJQXZ";
	if (strchr(array0, x))		return 0;
	if (strchr(array1, x))		return 1;
    if (strchr(array2, x))		return 2;
    if ( x == 'D' || x == 'T')	return 3;
    if ( x == 'L')				return 4;
    if ( x == 'M' || x == 'N')	return 5;
    if ( x == 'R')				return 6;
}

int main ()
{
    printf ("         NAME                     SOUNDEX CODE\n");
    char name [25];
    while(gets(name))
    {
        char output [25];
        output [0] = name [0];
        output [1] = output [2] = output [3] = '0';
        int code = soundexcode (name [0]);
        int index = 1;
        int length = strlen (name);
        for ( int i = 1; i < length; i++ )
        {
            int temp_code = soundexcode (name [i]);
            if(temp_code != code && temp_code != 0)
				output[index++] = temp_code + '0';
            if(temp_code != code) code = temp_code;
        }

        printf ("%9s%s", "", name);
        for ( int i = 0; i < 25 - length; i++ ) printf (" ");
        printf ("%c%c%c%c\n", output [0], output [1], 
			output [2], output [3]);
    }
    printf ("                   END OF OUTPUT\n");
    return 0;
}

Sample Input:

LEE
KUHNE
EBELL
EBELSON
SCHAEFER
SCHAAK

Sample Output:

         NAME                     SOUNDEX CODE
         LEE                      L000
         KUHNE                    K500
         EBELL                    E140
         EBELSON                  E142
         SCHAEFER                 S160
         SCHAAK                   S200
                   END OF OUTPUT

Runtime: 0.049s

UVa 100 Solution in c++

Complete Code:

#include<cstdio>

int main(){
	int i, j;
	while(scanf("%d %d", &i, &j)==2){
		//original order of i and j
		int ti = i, tj = j;
		//swapping i and j if i greater than j
		if(i>j){i=i+j;j=i-j;i=i-j;}
		int max = 0;
		while(i<=j){
			unsigned int count = 1, n = i;
			while(n!=1){
				if(n%2==1) n = 3*n+1;
				else n>>=1;
				count++;
			}
			if(max<count) max=count;
			i++;
		}
		printf("%d %d %d\n", ti, tj, max);
	}
	return 0;
}

Sample Input:

5 5
1 10
100 200
201 210
900 1000
1000 900
999999 999990

Sample Output:

5 5 6
1 10 20
100 200 125
201 210 89
900 1000 174
1000 900 174
999999 999990 259

Run Time: 0.532s