miércoles, 20 de marzo de 2024

Unlocking the Power of Quantum Computing: A Developer's Guide

Quantum computing is poised to revolutionize the way we approach complex computational problems, offering unparalleled processing power and the ability to solve certain tasks exponentially faster than classical computers. As developers, understanding and harnessing the potential of quantum computing opens up a realm of possibilities for tackling challenges across various domains. In this post, we'll delve into the basics of quantum computing and explore how developers can start testing quantum algorithms using Python and Qiskit.

Understanding Quantum Computing:

Quantum computing operates on the principles of quantum mechanics, leveraging quantum bits or qubits to perform computations. Unlike classical bits, which can only exist in states of 0 or 1, qubits can exist in superposition, representing both 0 and 1 simultaneously. This property allows quantum computers to explore multiple solutions to a problem simultaneously, leading to exponential speedup for certain algorithms.

Getting Started with Qiskit:

Qiskit is an open-source quantum computing framework developed by IBM, providing tools and libraries for quantum circuit design, simulation, and execution. To begin experimenting with quantum computing in Python, you'll need to install Qiskit using pip:

pip install qiskit

Once installed, you can import Qiskit modules in your Python code and start building quantum circuits.

Example: Implementing Grover's Algorithm in Qiskit:
Grover's algorithm is a quantum algorithm that efficiently searches an unsorted database, offering a quadratic speedup over classical search algorithms. Let's implement Grover's algorithm in Qiskit to search for a specific item in a list of binary strings.


from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram

# Define the number of qubits and the target item to search for
n = 4  # Number of qubits
target = '1010'  # Target item to search for

# Create a quantum circuit
qc = QuantumCircuit(n)

# Apply Hadamard gates to all qubits
qc.h(range(n))

# Define the oracle that marks the target item
for i in range(n):
    if target[i] == '0':
        qc.x(i)

qc.barrier()

# Apply controlled-Z gate (oracle)
qc.cz(0, 3)

qc.barrier()

# Apply Hadamard gates again
qc.h(range(n))

# Measure qubits
qc.measure_all()

# Simulate the circuit
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, simulator, shots=1024).result()

# Plot the results
counts = result.get_counts(qc)
plot_histogram(counts)

In this example, we define a quantum circuit with four qubits and apply the necessary gates to implement Grover's algorithm. We then simulate the circuit using Qiskit's built-in simulator and plot the measurement outcomes.

Conclusion:
Quantum computing represents a paradigm shift in computational capabilities, with the potential to revolutionize industries ranging from cryptography to drug discovery. As developers, embracing quantum computing opens up new avenues for innovation and problem-solving. By leveraging tools like Qiskit, we can begin exploring quantum algorithms and harnessing the power of quantum computing in our applications.

Note: While Qiskit provides simulators for testing quantum algorithms, accessing real quantum hardware may require collaboration with quantum computing providers such as IBM Quantum Experience.


jueves, 14 de marzo de 2024

Creating Business Applications connected to Artificial Intelligence Models

In the presentation, the speaker delves into the complexities of Enterprise AI, emphasizing understanding over mere terminology. They discuss the architecture behind Large Language Models (LLMs), challenges of scalability, security, and cost, and the importance of trust and risk management. Exploring the concept of assistants, they highlight the need for an intermediary layer to interact with LLMs, ensuring independence and reliability. They touch on memory management, data sources, and the evolution towards agent-driven systems. The talk underscores the necessity of thoughtful infrastructure and a robust assistant layer for effective enterprise applications in the AI era.




miércoles, 6 de marzo de 2024

Main Technology Tendencies in 2024

Introduction

As we delve deeper into the digital era, technology continues to evolve at a brisk pace, shaping our lives in unprecedented ways. In this blog post, we will explore three key technology trends that are set to dominate the landscape in 2024.

Artificial Intelligence (AI)

Artificial Intelligence continues to be a key trend in technology. In 2024, we will see more refined and sophisticated AI models, capable of performing complex tasks with minimal human intervention. Machine learning algorithms will be enhanced, leading to more precise predictions and decisions. AI is projected to permeate various industries, from healthcare, where it will assist doctors in diagnosing diseases, to the automotive industry, where it will drive the expansion of self-driving cars.

Internet of Things (IoT)

The Internet of Things (IoT) is another significant trend to watch out for in 2024. IoT refers to the network of physical objects embedded with sensors, software, and other technologies for the purpose of connecting and exchanging data with other devices and systems over the internet. These connected devices will become increasingly prevalent in our daily lives, from smart home appliances that sync with our smartphones to industrial IoT that improves manufacturing processes. The IoT industry will continue to grow, driven by the increasing need for automation and data-driven decision making.

Quantum Computing

Quantum computing, although still in its early stages, is set to make significant strides by 2024. Leveraging the principles of quantum physics, quantum computers can process data at a speed that is exponentially faster than traditional computers. This technology has the potential to revolutionize various fields, including cryptography, logistics, and drug discovery, by solving problems that are currently beyond the reach of classical computers.

Conclusion

In 2024, technology will continue to evolve and influence various aspects of our lives. From AI to IoT to quantum computing, these trends signify the dawn of a new era of innovation and disruption. As we move forward, it is essential for businesses and individuals to stay abreast of these trends and adapt accordingly to thrive in the ever-changing digital landscape.

jueves, 8 de febrero de 2024

Alternativas a Google Domains 2024

 ¿Utilizas hoy en día Google Domains? ¿Porque necesitas buscar una alternativa?

Google lanzó su servicio de registro de dominios en 2015 para ayudar a los usuarios a encontrar, comprar y gestionar un dominio para sus negocios. Sin embargo, Google Domains cerrará y Squarespace se hará cargo de los negocios y activos. Squarespace, conocido por ser un popular constructor de sitios web y proveedor de servicios de alojamiento, migrará a todos los clientes existentes y sus dominios a su plataforma. Aunque Squarespace respetará los precios de renovación de los clientes de Google Domains durante al menos 12 meses, se espera que los costos de renovación aumenten después de este período. Otros servicios de registro de dominios en el mercado ofrecen nombres de dominio gratuitos con planes de alojamiento, y los planes de alojamiento suelen ser más económicos que Squarespace.

Considerando estas alternativas, es importante explorar las mejores opciones disponibles tras el cierre de Google Domains.

Para la comparativa, obviamente no he usado todas las opciones que puedes encontrar sino que básicamente he comparado con aquellos que me dan confianza y he dejado fuera de la lista a algunos como Azure o AWS por la complejidad que suponen en la administración e incluso en el cálculo del precio.

AlternativaURLPrecio transferencia .com + 1º AñoPrecio .com /añoRegistroWeb HostingCloud ComputingCloud

Google Domainshttps://domains.google.com/N/A12.00€Si, Google SuiteSi, cualquier webSi, servicio completo

Domain.comhttps://www.domain.com/9.28€20.43€Si, Google SuiteSi, cualquier web



GoDaddyhttps://www.godaddy.com/es-es10.22€19.99€Si, Microsoft 365Si, cualquier web

Network Solutionshttps://www.networksolutions.com/9.28€23.23€Si, Google SuiteSi, cualquier web

Gandihttps://www.gandi.net/es13.77€24.19€Si, limitado a PHP, Python, Node

Squarespacehttps://domains.squarespace.com/N/A18.58€NoNo

Alibabahttps://www.alibabacloud.com/domain9.84€10.77€Si, Alibaba MailSi, cualquier webSi, servicio completo



Obviamente, si estas leyendo esto es porque como yo, en su día confiaste en Google Domains por varias razones entre ellas por la "reputación" de la compañía, las características que te ofrecía y por el precio tan competitivo que tenía.

Tras la compativa parece evidente que:
  • La mejor alternativa hoy en día por prestaciones y coste es Alibaba Domains.
  • Que las opciones más caras van desde Godaddy, Network Solutions o Gandi.
  • Y por supuesto que la opción de Squarespace, a la cual Google ha vendido su negocio de dominios es cara y muy ausente de prestaciones, por lo que al menos larebelion.com (en el momento de escribir este post, en Domains Google... migrará)


jueves, 14 de diciembre de 2023

Instalación servidor DNS en Raspberry PI

 Introducción

¿Que apetece tener un servicio de resolución de nombres interno en tu red local ya sea tu casa, tu laboratorio o entorno profesional?, una alternativa razonable al super conocido servicio DNS de Microsoft y encima open source, podría ser dnsmasq.

Manos a la obra

Lo primero que te recomiendo hacer es actualizar los paquetes de tu distribución, para ello debes seguir este sencillo pasos (2x1):

sudo apt update && apt upgrade -y
Una vez actualizados los paquetes, pasemos a lo más interesante, instalación de la suite dnsmasq (dnsmasq es excelente para redes pequeñas).

sudo apt install dnsmasq
Una vez instalado:

  1. Modifica el fichero dnsmasq.conf utilizando el editor que más te guste, yo usaré vim.
sudo vim /etc/dnsmasq.conf
2. Localiza las siguientes líneas y edita:

  • domain-needed - Configura el servidor DNS para que no reenvíe nombres sin un punto (.) o un nombre de dominio a servidores ascendentes. Los nombres sin punto o dominio permanecen en la red local.
  • bogus-priv - Evita que el servidor DNS reenvíe las consultas de búsqueda inversa del rango IP local a los servidores DNS ascendentes. De este modo, se evitan filtraciones de la red local a los servidores ascendentes.
  • no-resolv - Deja de leer los servidores de nombres upstream del archivo /etc/resolv.conf, confiando en su lugar en los de la configuración de DNSMasq.

3. Guarda los cambios en el fichero y reinicia el servicio:

sudo systemctl restart dnsmasq
4. Verifica el estatus del servicio.

sudo systemctl status dnsmasq

5. Prueba que esté funcionando desde la raspberry.


6. Pruébalo desde otra computadora en la red.







sábado, 25 de noviembre de 2023

What is the tech stack for the shortern future?

Predicting the exact technology stack for the future can be challenging because technology evolves rapidly, and new innovations constantly emerge. However, there are some trends and technologies that have been gaining traction and are likely to play a significant role in the tech stacks of the future. Keep in mind that the specific stack you choose will depend on your project's requirements and goals. Here are some key trends and technologies to consider:


  • Cloud Computing: Cloud platforms like Amazon Web Services (AWS), Microsoft Azure, and Google Cloud are expected to continue dominating the cloud computing landscape. Serverless computing and containerization (using technologies like Docker and Kubernetes) will likely become even more important for scalability and efficiency.

  • Edge Computing: As IoT devices become more prevalent, edge computing will grow in importance. This involves processing data closer to the source (i.e., the "edge" of the network) to reduce latency and improve real-time decision-making.

  • Artificial Intelligence (AI) and Machine Learning (ML): AI and ML will continue to be integrated into various applications and services. Frameworks like TensorFlow and PyTorch will remain important, and AI/ML models will be increasingly deployed at the edge for faster processing.

  • Blockchain: While blockchain technology is primarily associated with cryptocurrencies like Bitcoin, it has applications beyond finance, such as supply chain management, voting systems, and more. Blockchain platforms like Ethereum and Hyperledger are likely to see continued development and adoption.

  • Quantum Computing: Quantum computing is still in its infancy, but it holds great promise for solving complex problems that are currently beyond the capabilities of classical computers. Companies like IBM and Google are actively working on quantum computing research.

  • 5G Technology: The rollout of 5G networks will enable faster and more reliable wireless connectivity. This will impact various industries, including IoT, autonomous vehicles, augmented reality, and virtual reality.

  • Cybersecurity: With the increasing importance of digital data and connectivity, cybersecurity will remain a top concern. Technologies like AI-driven threat detection, zero-trust security models, and encryption will continue to evolve.

  • Web Technologies: JavaScript, HTML, and CSS will remain fundamental for web development, but frameworks like React, Angular, and Vue.js are likely to continue their popularity. Progressive Web Apps (PWAs) and WebAssembly are also promising technologies.

  • DevOps and Automation: DevOps practices, along with tools like Jenkins, Docker, and Ansible, will continue to streamline development, deployment, and operations processes. Automation will be critical for efficiency and reliability.

  • Sustainability: Sustainability considerations will play a larger role in tech stacks. Energy-efficient hardware, green data centers, and eco-friendly software development practices will become more important.

  • AR/VR: Augmented reality (AR) and virtual reality (VR) technologies will continue to advance, with applications in gaming, education, healthcare, and more.

  • Natural Language Processing (NLP): NLP technologies like GPT-4 and beyond will enable more sophisticated conversational AI, language translation, and content generation.

  • Container Orchestration: Technologies like Kubernetes and Docker Swarm will remain crucial for managing and scaling containerized applications.


It's essential to stay up-to-date with emerging technologies and adapt your tech stack based on your project's specific needs and the evolving industry trends. Flexibility and a willingness to learn and experiment will be valuable skills for technology professionals in the future. 

viernes, 27 de octubre de 2023

JAVA: ¿Porque nos hacen aprender JAVA en la Universidad?

 Aprender Java es importante por varias razones:

  1. Amplia demanda laboral: Java es uno de los lenguajes de programación más populares y ampliamente utilizados en la industria de la tecnología. Muchas empresas buscan desarrolladores de Java, lo que significa que hay una gran demanda laboral en este campo. Aprender Java puede abrirte puertas en el mercado laboral y aumentar tus oportunidades de empleo.
  2. Versatilidad: Java se utiliza en una amplia variedad de aplicaciones, desde desarrollo web hasta aplicaciones móviles, sistemas embebidos, aplicaciones de escritorio y más. Esto significa que puedes aplicar tus conocimientos de Java en una variedad de proyectos y contextos.
  3. Plataforma independiente: Java es conocido por su capacidad de ser ejecutado en múltiples plataformas. Esto se debe a la máquina virtual Java (JVM), que permite que el código Java se ejecute en diferentes sistemas operativos sin necesidad de modificaciones importantes. Esto lo hace ideal para aplicaciones empresariales que deben ser compatibles con diversas plataformas.
  4. Comunidad y recursos: Java tiene una gran comunidad de desarrolladores y una amplia cantidad de recursos de aprendizaje disponibles en línea, como tutoriales, documentación oficial y foros de discusión. Esto facilita el proceso de aprendizaje y resolución de problemas.
  5. Seguridad y robustez: Java está diseñado con un enfoque en la seguridad y la robustez. Tiene características que ayudan a prevenir vulnerabilidades comunes de seguridad y a gestionar eficazmente la memoria, lo que reduce la posibilidad de errores graves en el código.
  6. Orientación a objetos: Java es un lenguaje orientado a objetos, lo que significa que se basa en un modelo de programación que se asemeja a cómo pensamos y organizamos conceptos en el mundo real. Esto facilita la creación de software modular y mantenible.
  7. Frameworks y bibliotecas: Java cuenta con una amplia variedad de frameworks y bibliotecas que simplifican el desarrollo de aplicaciones en diferentes dominios, como Spring para desarrollo web, Android para aplicaciones móviles y Hibernate para acceso a bases de datos, entre otros.
  8. Carrera a largo plazo: Aprender Java puede proporcionarte una base sólida para tu carrera en el desarrollo de software. A medida que adquieras experiencia, podrás especializarte en áreas específicas de desarrollo, como el desarrollo web, la inteligencia artificial o el desarrollo de aplicaciones móviles, todo mientras sigues utilizando Java como base.

Random r1 = new Random();
Random r2 = new Random(47);
Random r3 = new Random(47); // r2 y r3 darán la misma secuencia.
  
int n1 = r1.nextInt();
int n2 = r2.nextInt(10); // número aleatorio entre 0 y 9 (el 10 es exclusive)
int n3 = r3.nextInt(10); // obtendremos el mismo número aleatorio que n2, ya que ambos usan la misma semilla
  
System.out.println("n1: " + n1);
System.out.println("n2: " + n2);
System.out.println("n3: " + n3);


En resumen, aprender Java es importante debido a su amplia demanda en el mercado laboral, su versatilidad, su capacidad de ser utilizado en diversas plataformas y su sólida comunidad de desarrollo. Ya sea que estés buscando una carrera en programación o quieras expandir tus habilidades en el desarrollo de software, Java es un lenguaje que vale la pena aprender.

viernes, 29 de septiembre de 2023

Domina Java: 20 Ejercicios Resueltos para Impulsar tus Habilidades de Programación. Universidad. (Parte 2)

 Como continuación del artículo "Domina Java: 20 Ejercicios Resueltos para Impulsar tus Habilidades de Programación. Universidad. (Parte 1)", aqui publico la Parte 2 del artículo que no es más que una continuación con otros 20 ejercicios prácticos para que pongais en juego lo aprendido en la universidad o vuestros cursos de programación de Java.


Ejercicio 21: Programa Java de búsqueda lineal

import java.util.Scanner;

class Main {
  public static void main(String[] args) {

    int[] numbers = {4,2,7,1,8,3,6};
    int flag = 0;
    
    System.out.println("Enter the number to be found out: ");
    Scanner sc = new Scanner(System.in);
    int x = Integer.parseInt(sc.nextLine());
    
    for(int i=0;i<numbers.length;i++){
      if (x==numbers[i]){
        System.out.println("Successful search, the element is found at position "+ i);
        flag = 1;
        break;
      }
    }

    if(flag==0){
      System.out.println("Oops! Search unsuccessful");
    }
    
  }
}


Ejercicio 22: Programa Java de búsqueda binaria

import java.util.Scanner;

class Main {
  public static void main(String[] args) {

    int[] numbers = {1,4,6,7,12,17,25}; //binary search requires sorted numbers
    System.out.println("Enter the number to be found out: ");
    Scanner sc = new Scanner(System.in);
    int x = Integer.parseInt(sc.nextLine());

    int result = binarySearch(numbers, 0, numbers.length-1, x);
    if (result != -1)
      System.out.println("Search successful, element found at position "+result);
    else
      System.out.println("The given element is not present in the array");
    
  }

  public static int binarySearch(int[] numbers,int low,int high,int x){
    if (high >= low){
      int mid = low + (high - low)/2;
      if (numbers[mid] == x)
        return mid;
      else if (numbers[mid] > x)
        return binarySearch(numbers, low, mid-1, x);
      else
        return binarySearch(numbers, mid+1, high, x);
    }else{
      return -1;
    }
        
        
  }
}


Ejercicio 23: Programa Java para encontrar el número de números impares en una matriz

class Main {
  public static void main(String[] args) {

    int[] numbers = {8,3,1,6,2,4,5,9};
    int count = 0;

    for(int i=0;i<numbers.length;i++){
      if(numbers[i]%2!=0)
        count++;
    }
   System.out.println("The number of odd numbers in the list are: "+count);      
        
  }
}


Ejercicio 24: Programa Java para encontrar el mayor número de una matriz sin utilizar funciones incorporadas

class Main {
  public static void main(String[] args) {

    int[] numbers = {3,8,1,7,2,9,5,4};
    int largest = numbers[0];
    int position = 0;

    for(int i=0;i<numbers.length;i++){
      if(numbers[i]>largest){
        largest = numbers[i];
        position = i;
      }
    }

   System.out.println("The largest element is "+largest+" which is found at position "+position);      
        
  }
}


Ejercicio 25: Programa Java para insertar un número en cualquier posición de una matriz

import java.util.Scanner;
import java.util.Arrays;

class Main {
  public static void main(String[] args) {

    int[] numbers = {3,4,1,9,6,2,8};
    System.out.println(Arrays.toString(numbers));

    System.out.println("Enter the number to be inserted: ");
    Scanner sc = new Scanner(System.in);
    int x = Integer.parseInt(sc.nextLine());
    System.out.println("Enter the position: ");
    int y = Integer.parseInt(sc.nextLine());

    for(int i=numbers.length-1;i>y;i--){
        numbers[i] = numbers[i-1];
    }
    numbers[y] = x;

   System.out.println(Arrays.toString(numbers));   
        
  }
}


Ejercicio 26: Programa Java para borrar un elemento de un array por índice

import java.util.Scanner;
import java.util.Arrays;

import java.util.ArrayList; 

class Main {
  public static void main(String[] args) {

    ArrayList<Integer> numbers = new ArrayList<Integer>(5); 
    numbers.add(3);
    numbers.add(7);
    numbers.add(1);
    numbers.add(4);
    
    System.out.println(numbers);

    System.out.println("Enter the position of the element to be deleted: ");
    Scanner sc = new Scanner(System.in);
    int x = Integer.parseInt(sc.nextLine());

    numbers.remove(x);

   System.out.println(numbers);   
        
  }
}


Ejercicio 27: Programa Java para comprobar si una cadena es un palíndromo o no

import java.util.Scanner;  

class Main {
  public static void main(String[] args) {

    String a, b = "";
    Scanner s = new Scanner(System.in);
    System.out.print("Enter the string you want to check: ");
    a = s.nextLine();
    
    int n = a.length();
    for(int i = n - 1; i >= 0; i--){
        b = b + a.charAt(i);
    }
    
    if(a.equalsIgnoreCase(b)){
      System.out.println("The string is a palindrome.");
    }else{
      System.out.println("The string is not a palindrome.");
    }
    
  }
}


Ejercicio 28: Programa Java para la suma de matrices

class Main {
  public static void main(String[] args) {

    //creating two matrices    
    int a[][]={{8,5,1},{9,3,2},{4,6,3}};    
    int b[][]={{8,5,3},{9,5,7},{9,4,1}};    
    
    //matrix to store the sum of two matrices    
    int c[][]=new int[3][3];  //3 rows and 3 columns  
    
    //adding 2 matrices    
    for(int i=0;i<3;i++){    
      for(int j=0;j<3;j++){    
        c[i][j]=a[i][j]+b[i][j];
        System.out.print(c[i][j]+" ");    
      }
      System.out.print("\n"); 
    }    
    
  }
}


Ejercicio 29: Programa Java para la multiplicación de matrices

class Main {
  public static void main(String[] args) {

    //creating two matrices    
    int a[][]={{8,5,1},{9,3,2},{4,6,3}};    
    int b[][]={{8,5,3},{9,5,7},{9,4,1}};    
    
    //matrix to store the product of two matrices    
    int c[][]=new int[3][3];
    
    //multiplying 2 matrices
    for(int i=0;i<3;i++){    
      for(int j=0;j<3;j++){    
        c[i][j]=0;      
        for(int k=0;k<3;k++){      
          c[i][j]+=a[i][k]*b[k][j];      
        }
        System.out.print(c[i][j]+" ");
      }
      System.out.print("\n"); 
    }    
    
  }
}


Ejercicio 30: Programa Java para comprobar el año bisiesto

import java.util.Scanner;  

class Main {
  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    System.out.print("Enter the year you want to check: ");
    int year = Integer.parseInt(sc.nextLine()); 
    boolean leap = false;
    
    // if the year is divided by 4
    if (year % 4 == 0) {
      // if the year is century
      if (year % 100 == 0) {
        // if year is divided by 400, then it is a leap year
        if (year % 400 == 0)
          leap = true;
        else
          leap = false;
      }
      // if the year is not century
      else
        leap = true;
    }
    else
      leap = false;

    if (leap)
      System.out.println(year + " is a leap year.");
    else
      System.out.println(year + " is not a leap year.");
    
  }
}


Ejercicio 31: Programa Java para hallar el enésimo término de una serie de Fibonacci mediante recursión

import java.util.Scanner;  

class Main {
  public static void main(String[] args) {
    Scanner cs=new Scanner(System.in);
    int n;
		System.out.print("Enter the position(N): ");
		n=cs.nextInt();
		System.out.print("Nth Fibonacci Number is: "+NthFibonacciNumber(n));
  }

  static int NthFibonacciNumber(int n){
	    if(n==1)
	        return 0;
	    else if(n==2)
	        return 1;
	    else
	        return NthFibonacciNumber(n-1)+NthFibonacciNumber(n-2);
	}
  
}


Ejercicio 32: Programa Java para imprimir series Fibonacci usando iteración

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    int n1=0,n2=1;
    Scanner cs=new Scanner(System.in);
		System.out.print("Enter the number of terms in the sequence: ");
		int count = cs.nextInt(); 
    int n3,i;
    
    System.out.print(n1+" "+n2);//printing 0 and 1
    //printing from 2 because 0 and 1 are already printed  
    for(i=2;i<count;++i){
      n3=n1+n2;    
      System.out.print(" "+n3);    
      n1=n2;    
      n2=n3;
      }    
	
    }
}


Ejercicio 33: Programa Java para implementar una calculadora que realice operaciones básicas

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
      int firstNumber, secondNumber, opt, add, sub, mul;
      double div;
      Scanner s = new Scanner(System.in);
      System.out.print("Enter first number: ");
      firstNumber = s.nextInt();
      System.out.print("Enter second number: ");
      secondNumber = s.nextInt();
      
      while(true){
        System.out.println("Enter 1 for addition");
        System.out.println("Enter 2 for subtraction");
        System.out.println("Enter 3 for multiplication");
        System.out.println("Enter 4 for division");
        System.out.println("Enter 5 to Exit");
        int option = s.nextInt();
        switch(option){
          case 1:
            add = firstNumber + secondNumber;
            System.out.println("Result:"+add);
            break;
 
          case 2:
            sub = firstNumber - secondNumber;
            System.out.println("Result:"+sub);
            break;
 
          case 3:
            mul = firstNumber * secondNumber;
            System.out.println("Result:"+mul);
            break;
 
          case 4:
            div = (double)firstNumber / secondNumber;
            System.out.println("Result:"+div);
            break;    
 
          case 5:
            System.exit(0);
            
            }
        }
	
    }
}


Ejercicio 34: Programa Java para encontrar tu peso en Marte

import java.util.Scanner;  

class Main {
  public static void main(String[] args) {

  Scanner input = new Scanner(System.in);
  System.out.print("How many pounds (lbs) do you weigh? ") ;
  float weight = input.nextFloat();

  // computing the weight on mars
  double weightOnMars = (weight * .38);

  // displaying results with 4 decimal places
  System.out.println("Your weight is "+String.format("%.4f",weightOnMars)+" lbs on Mars");

    System.out.println("Converting the variable into integer");
    int weightOnMarsInt = (int)weightOnMars;
    System.out.println(weightOnMarsInt);

    System.out.println("Converting the variable into char");
    char weightOnMarsChar = (char)weightOnMars;
    System.out.println(weightOnMarsChar);

    System.out.println("Converting the variable into Int and doing an operation on it");
    int newIntVariable = weightOnMarsChar * 2;
    System.out.println(newIntVariable);
    
  }
}


Ejercicio 35: Programa Java para comprobar si el número aleatorio generado es par o impar

import java.util.Random;

class Main {
  public static void main(String[] args) {

    int min = 1;
    int max = 100;

    //Generating a random number
    Random r = new Random();
    int randomNumber = min + r.nextInt(max);
    System.out.println("Generated random number is: "+randomNumber);

    //Checking whether the number is odd or even

    if(randomNumber%2==0){
      System.out.println("The generated random number is even.");
    }else{
      System.out.println("The generated random number is odd.");
    }
        
  }
}


Ejercicio 36: Programa Java para calcular el número de contenedores necesarios

import java.util.Scanner;

class Main {
  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    System.out.println("How many Lego bricks do we have? Choose an odd number between 50 and 100: ");
    int amountOfBricks = Integer.parseInt(sc.nextLine());

    System.out.println("How many Lego blocks fit in one container? Choose an even number between 5 and 10: ");
    int containerCapacity = Integer.parseInt(sc.nextLine());

    int noOfFullContainers = amountOfBricks/containerCapacity;
    int noOfTotalContainers;

    int noOfBlocksInNotFullContainers = amountOfBricks%containerCapacity;

    if(noOfBlocksInNotFullContainers!=0){
      noOfTotalContainers = noOfFullContainers + 1;
    }else{
      noOfTotalContainers = noOfFullContainers;
    }
    
    System.out.println("No of full containers we have: "+noOfFullContainers);
    System.out.println("No of total containers we have: "+noOfTotalContainers);
    System.out.println("No of blocks in the container that is not completely full: "+noOfBlocksInNotFullContainers);
        
  }
}


Ejercicio 37: Programa Java para calcular impuestos

import java.math.BigDecimal;    

class Main {
  public static void main(String[] args) {

    double netValue = 9.99;
    double VAT = 23.0;

    //calculating grossValue
    double grossValue = netValue + (VAT*netValue/100);
    System.out.println("The gross value is: "+grossValue);

    // multiplying the value by 10000
    double grossValue10000 = grossValue * 10000;
    System.out.println("The gross value for 10000 units is: "+grossValue10000);

    // calculating price excluding VAT 23%
    double excludingVAT = grossValue10000 - (VAT*grossValue10000/100);
    System.out.println("The value for 10000 units excluding VAT is: "+excludingVAT);

    // doing the same operations using BigDecimal instead of double
     System.out.println("\n----Using BigDecimal instead of double----\n");
       
    BigDecimal netValue_big = new BigDecimal("9.99");
    BigDecimal VAT_big = new BigDecimal("23.0");
    BigDecimal HUNDRED = new BigDecimal("100");
    BigDecimal TenThousand = new BigDecimal("10000");

    //calculating grossValue
    BigDecimal grossValue_big = netValue_big.add(VAT_big.multiply(netValue_big.divide(HUNDRED)));
    System.out.println("The gross value is: "+grossValue_big);
    
    // multiplying the value by 10000
    BigDecimal grossValue10000_big = grossValue_big.multiply(TenThousand);
    System.out.println("The gross value for 10000 units is: "+grossValue10000_big);
    
    // calculating price excluding VAT 23%
    BigDecimal excludingVAT_big = grossValue10000_big.subtract(VAT_big.multiply(grossValue10000_big.divide(HUNDRED)));
    System.out.println("The value for 10000 units excluding VAT is: "+excludingVAT_big);


  System.out.println("\nThe accuracy is higher when we use BigDecimal instead of double");
    
  }
}


Ejercicio 38: Calcular el IMC con Java

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    float height, weight, bmi;
    Scanner s = new Scanner(System.in);
    System.out.println("Enter the height (in inches): ");
    height = s.nextFloat();
    System.out.println("Enter the weight (in pounds): ");
    weight = s.nextFloat();
    bmi = (float)(weight / Math.pow(height, 2) * 703);

    System.out.println("The BMI is: "+bmi);

    if(bmi<16.00)
      System.out.println("starvation");
    else if(bmi>=16.00 && bmi <= 16.99)
      System.out.println("emaciation");
    else if(bmi>=17.00 && bmi <= 18.49)
      System.out.println("underweight");
    else if(bmi>=18.50 && bmi<=22.99)
      System.out.println("normal, low range");
    else if(bmi>=23.00 && bmi<=24.99)
      System.out.println("normal, high range");
    else if(bmi>=25.00 && bmi<=27.49)
      System.out.println("overweight, low range");
    else if(bmi>=27.50 && bmi<=29.99)
      System.out.println("overweight, high range");
    else if(bmi>=30.00 && bmi<=34.9)
      System.out.println("1st degree obesity");
    else if(bmi>=35.00 && bmi<=39.90)
      System.out.println("2nd degree obesity");
    else
      System.out.println("3rd degree obesity");
  
    }
}


Ejercicio 39: Programa Java para hallar la suma de números pares

class Main {
  public static void main(String[] args) {
      int sum=0;
    
      for(int i=1;i<=100;i++){
        if(i%2==0){
          sum = sum + i;
        }
      }

      System.out.println("The sum of even numbers from 1-100 is: "+sum);
    
    }
}


Ejercicio 40: Programa Java para encontrar los números más grandes y más pequeños a partir de números aleatorios

import java.util.Random;

class Main {
  public static void main(String[] args) {
    int min = 1, max=100;
    int largest=0;
    int smallest=100;
    int i = 1;
    
    while(i<=10){
      //Generating a random number
      Random r = new Random();
      int randomNumber = min + r.nextInt(max);
      System.out.println("Generated random number is: "+randomNumber);
      if(randomNumber>largest){
        largest = randomNumber;
      }
      if(randomNumber<smallest){
        smallest = randomNumber;
      }
      i++;
    }
    
    System.out.println("\n");
    System.out.println("The smallest number is: "+smallest);
    System.out.println("The largest number is: "+largest);
    
  }
}