some image

Challenges

Solucionando : Small Factorials

Etiquetas: , Blog, Challenges No comments

Este ejercicio pertenece a la categoría easy de codechef y aunque realmente no tiene un grado de complejidad elevado, el punto clave es que tan rápido puede arrojar los resultados obteniendo el factorial de un 1 <= n <= 100.  Bien aqui está el planteamiento de mi solución utilizando la clase BigInteger y un pequeño ciclo for.

 

import java.math.BigInteger;
import java.util.Scanner;
class SmallFactorial {
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		//Lines to processs
		int lines = sc.nextInt();
		for(int i = 0;  i < lines; i++){
			int n = sc.nextInt();
			BigInteger fac = BigInteger.ONE;
			//Get the Factorial
			for (int j = 1; j <= n; j++) {
				fac = fac.multiply(BigInteger.valueOf(j));
			}
			System.out.println(fac);
		}
	}
}

Salu2

Solucionando Problem 7 – Project Euler

Etiquetas: , Blog, Challenges No comments

Para solucionar este problema, recurrí a una solución algo simple teniendo en cuenta los métodos ya implementados por la clase BigInteger, llamando puntualmente al metodo nextProbablePrime() e iterando hasta llegar a la posición del número primo requerido. :)

Problema

 By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see
 that the 6th prime is 13.
  
 What is the 10 001st prime number?

Solución

import java.math.BigInteger;

/**
 * By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see
 * that the 6th prime is 13.
 * 
 * What is the 10 001st prime number?
 * 
 * @author codesandtags
 * 
 */
public class Problem7 {

	public static void main(String[] args) {
		Problem7 solve = new Problem7();
		System.out.println("The 10001st prime number is : "
				+ solve.getPrimeNumber(6));
		System.out.println("The 10001st prime number is : "
				+ solve.getPrimeNumber(10001));
	}

	/**
	 * Obtiene un numero primo dado
	 * 
	 * @param n
	 * @return
	 */
	public BigInteger getPrimeNumber(int n) {
		// Inicializa el primer numero primo
		BigInteger prime = BigInteger.ZERO;
		// Itera hasta llegar a N primos
		for (int i = 0; i < n; i++) {
			prime = prime.nextProbablePrime();
		}
		// Hakuna Matata
		return prime;
	}
}

Hakuna Matata

Solucionando Problem 6 – Project Euler

Etiquetas: , Blog, Challenges No comments

Este problema consistia en hallar la diferencia entre la suma de los primeros X cuadrados y el cuadrado de la suma de los primeros X numeros :).

Problema

 The sum of the squares of the first ten natural numbers is,
 
 12 + 22 + ... + 102 = 385 The square of the sum of the first ten natural
 numbers is,
  
 (1 + 2 + ... + 10)2 = 552 = 3025 Hence the difference between the sum of the
 squares of the first ten natural numbers and the square of the sum is 3025
 385 = 2640.
  
 Find the difference between the sum of the squares of the first one hundred
 natural numbers and the square of the sum.

Solución

/**
 * The sum of the squares of the first ten natural numbers is,
 * 
 * 12 + 22 + ... + 102 = 385 The square of the sum of the first ten natural
 * numbers is,
 * 
 * (1 + 2 + ... + 10)2 = 552 = 3025 Hence the difference between the sum of the
 * squares of the first ten natural numbers and the square of the sum is 3025
 * 385 = 2640.
 * 
 * Find the difference between the sum of the squares of the first one hundred
 * natural numbers and the square of the sum.
 * 
 * @author codesandtags
 * 
 */
public class Problem6 {

	public static void main(String[] args) {

		Problem6 solve = new Problem6();
		System.out.println("The sum of the squares is : "
				+ solve.differenceSumSquares(10));
		System.out.println("The sum of the squares is : "
				+ solve.differenceSumSquares(100));

	}

	/**
	 * Obtiene la diferencia entre el cuadrado de los primeros X numeros y de
	 * cada uno de los primeros X numeros dados
	 * 
	 * @param square
	 * @return
	 */
	public long differenceSumSquares(int square) {
		// Variables
		long sumSquares = 0;
		long sumNumbers = 0;
		long difference = 0;

		// Itera para hallar la suma de los cuadrados y los numeros
		for (int i = 1; i <= square; i++) {
			sumSquares += (long) Math.pow(i, 2);
			sumNumbers += i;
		}
		// Se obtiene la diferencia
		difference = (long) (Math.pow(sumNumbers, 2) - sumSquares);
		return difference;
	}
}

Hakuna Matata

Solucionando Problem 17 – Project Euler

Etiquetas: , Blog, Challenges No comments

Para solucionar este problema, tuve que pensar en un tipo de sistema de notación de números a letras (con el nombre del número). Para esto tuve en cuenta las reglas dadas en el problema de Project Euler, y una vez realizada la conversión se procedió a sumar la longitud de cada palabra.

Consideraciones a tener en cuenta
+ A medida que los numeros son más grandes, decenas, centenas, miles, etc.. se debe emplear el respectivo mod para ir reduciendo el número hasta llegar a cero.
+ considero que puede haber formas mucho más eficientes de hacer este problema, aunque en esta ocación esta fue mi solución 😛

Problema

 If the numbers 1 to 5 are written out in words: one, two, three, four, five,
 then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
 
 If all the numbers from 1 to 1000 (one thousand) inclusive were written out
 in words, how many letters would be used? 
 
 NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and
 forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20
 letters. The use of "and" when writing out numbers is in compliance with
 British usage.

Solución

/**
 * 
 * If the numbers 1 to 5 are written out in words: one, two, three, four, five,
 * then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
 * 
 * If all the numbers from 1 to 1000 (one thousand) inclusive were written out
 * in words, how many letters would be used? 
 * 
 * NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and
 * forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20
 * letters. The use of "and" when writing out numbers is in compliance with
 * British usage.
 * 
 * @author codesandtags
 * 
 */

public class Problem17 {
	public static void main(String[] args) {
		Problem17 solve = new Problem17();
		System.out.println("=> " + solve.getNumberOfLetters(1000) + " letters");
	}

	/**
	 * Obtiene la cantidad de letras que contienen las palabras desde el numero
	 * uno hasta un maximo numero especificado
	 * 
	 * @param maxNumber
	 * @return
	 */
	public int getNumberOfLetters(int maxNumber) {
		int letters = 0;

		for (int i = 1; i <= maxNumber; i++) {
			letters += getNumberInWord(i).length();
			System.out.println(i + " => " + getNumberInWord(i));
		}

		return letters;
	}

	/**
	 * Devuelve en palabras un numero dado
	 * 
	 * @param number
	 * @return
	 */
	public String getNumberInWord(int number) {
		//Palabra del numero dado
		StringBuilder word = new StringBuilder();
		
		//Mientras que el numero sea diferente de cero sigue operando
		while (number != 0) {
			if (number < 10) {
				// System.out.println("antes number " + number);
				if (number == 1)	word.append("one");
				if (number == 2)	word.append("two");
				if (number == 3)	word.append("three");
				if (number == 4)	word.append("four");
				if (number == 5)	word.append("five");
				if (number == 6)	word.append("six");
				if (number == 7)	word.append("seven");
				if (number == 8)	word.append("eight");
				if (number == 9)	word.append("nine");
				number = 0;
				// System.out.println("despues number " + number);
			} else if (number >= 10 && number < 100) {
				// System.out.println("antes number " + number);
				if (number >= 10 && number < 20) {
					if (number == 10)	word.append("ten");
					if (number == 11)	word.append("eleven");
					if (number == 12)	word.append("twelve");
					if (number == 13)	word.append("thirteen");
					if (number == 14)	word.append("fourteen");
					if (number == 15)	word.append("fifteen");
					if (number == 16)	word.append("sixteen");
					if (number == 17)	word.append("seventeen");
					if (number == 18)	word.append("eighteen");
					if (number == 19)	word.append("nineteen");
					number = 0;
				} else {
					if (number >= 20 && number <= 29)	word.append("twenty");
					if (number >= 30 && number <= 39)	word.append("thirty");
					if (number >= 40 && number <= 49)	word.append("forty");
					if (number >= 50 && number <= 59)	word.append("fifty");
					if (number >= 60 && number <= 69)	word.append("sixty");
					if (number >= 70 && number <= 79)	word.append("seventy");
					if (number >= 80 && number <= 89)	word.append("eighty");
					if (number >= 90 && number <= 99)	word.append("ninety");
				}
				//Mod 10
				number %= 10;
			} else if (number >= 100 && number < 1000) {				
				if (number >= 100 && number <= 199)	word.append("onehundred");
				if (number >= 200 && number <= 299)	word.append("twohundred");
				if (number >= 300 && number <= 399)	word.append("threehundred");
				if (number >= 400 && number <= 499)	word.append("fourhundred");
				if (number >= 500 && number <= 599)	word.append("fivehundred");
				if (number >= 600 && number <= 699)	word.append("sixhundred");
				if (number >= 700 && number <= 799)	word.append("sevenhundred");
				if (number >= 800 && number <= 899)	word.append("eighthundred");
				if (number >= 900 && number <= 999)	word.append("ninehundred");
				if(number % 100 >= 1){
					word.append("and");
				}
				//Mod 100
				number %= 100;
			} else if (number >= 1000 && number < 10000) {
				if (number >= 1000 && number <= 1999)	word.append("onethousand");
				//Mod 1000 ... Be contined...
				number %= 1000;
			}
		}

		// Hakuna Matata
		return word.toString();
	}
}

Solucionando Problem 5 – Project Euler

Etiquetas: , Blog, Challenges No comments

Este problema consistía en encontrar el número más pequeño que fuera divisible por todos los números inferiores a 20, que no tuviesen un residuo. La clave para solucionar este problema es el manejo de flags.

Problema

  2520 is the smallest number that can be divided by each of the numbers from 1
  to 10 without any remainder.
  
  What is the smallest positive number that is evenly divisible by all of the
  numbers from 1 to 20?

Solución

/**
 * 2520 is the smallest number that can be divided by each of the numbers from 1
 * to 10 without any remainder.
 * 
 * What is the smallest positive number that is evenly divisible by all of the
 * numbers from 1 to 20?
 * 
 * @author codesandtags
 * 
 */

public class Problem5 {

	public static void main(String[] args) {

		Problem5 solve = new Problem5();
		System.out.println("The Smallest positive number divisible of 20 : "
				+ solve.smallestDivisible(20));

	}

	/**
	 * 
	 * @param num
	 * @return
	 */
	public int smallestDivisible(int num) {
		// El numero mas pequeño
		int smallest = 0;
		// Flag para manejar la condicion
		boolean isSmallest = false;

		// Itera hasta que encuentre el primer numero divisible por todos los
		// numeros descendientes de manera secuencial de un numero dado
		while (!isSmallest) {
			smallest++;

			// Obtiene un numero divisible sin resto hasta que se hallen todos
			// los numeros
			for (int k = num; k > 0; k--) {
				if (smallest % k == 0) {
					isSmallest = true;
				} else {
					// Si no es divisible rompe y continua con el proximo numero
					isSmallest = false;
					break;
				}
			}
		}

		return smallest;
	}

}