Kotlin Long

Introduction

In Kotlin, the Long class represents a 64-bit signed integer. It is used for numerical values that require a larger range than the Int class. The Long class provides various methods to perform arithmetic operations, comparisons, and type conversions.

Table of Contents

  1. What is the Long Class?
  2. Creating Long Values
  3. Long Operations
  4. Long Functions
  5. Examples of Long
  6. Real-World Use Case
  7. Conclusion

1. What is the Long Class?

The Long class in Kotlin is a wrapper for the primitive long type. It provides methods and properties to work with 64-bit signed integer values. Long integers are used for numerical calculations that require a larger range than Int.

Syntax

val myLong: Long = 123456789L

2. Creating Long Values

You can create Long values using literals with an L or l suffix, or by converting other numeric types to Long.

Example

fun main() {
    val a: Long = 123456789L
    val b = 987654321L
    val c = "1234567890123456789".toLong()

    println("a: $a, b: $b, c: $c")
}

3. Long Operations

Kotlin supports various operations on Long values, including arithmetic and comparison operations.

Arithmetic Operations

  • + (Addition)
  • - (Subtraction)
  • * (Multiplication)
  • / (Division)
  • % (Modulus)

Example

fun main() {
    val a: Long = 10000000000L
    val b: Long = 2000000000L

    val sum = a + b
    val difference = a - b
    val product = a * b
    val quotient = a / b
    val remainder = a % b

    println("Sum: $sum")
    println("Difference: $difference")
    println("Product: $product")
    println("Quotient: $quotient")
    println("Remainder: $remainder")
}

Comparison Operations

  • == (Equal to)
  • != (Not equal to)
  • < (Less than)
  • > (Greater than)
  • <= (Less than or equal to)
  • >= (Greater than or equal to)

Example

fun main() {
    val a: Long = 10000000000L
    val b: Long = 2000000000L

    println("a == b: ${a == b}")
    println("a != b: ${a != b}")
    println("a < b: ${a < b}")
    println("a > b: ${a > b}")
    println("a <= b: ${a <= b}")
    println("a >= b: ${a >= b}")
}

4. Long Functions

The Long class provides several useful functions:

  • toByte(): Converts the value to a Byte.
  • toShort(): Converts the value to a Short.
  • toInt(): Converts the value to an Int.
  • toFloat(): Converts the value to a Float.
  • toDouble(): Converts the value to a Double.
  • toString(): Converts the value to a String.
  • compareTo(other: Long): Compares this value with another Long.

Example

fun main() {
    val a: Long = 1234567890123456789L

    println("toByte: ${a.toByte()}")
    println("toShort: ${a.toShort()}")
    println("toInt: ${a.toInt()}")
    println("toFloat: ${a.toFloat()}")
    println("toDouble: ${a.toDouble()}")
    println("toString: ${a.toString()}")
    println("compareTo 1000000000L: ${a.compareTo(1000000000L)}")
}

5. Examples of Long

Example 1: Calculating Factorial

This example demonstrates using Long to calculate the factorial of a number.

fun factorial(n: Long): Long {
    return if (n == 1L) n else n * factorial(n - 1)
}

fun main() {
    val num = 20L
    val result = factorial(num)
    println("Factorial of $num is $result")
}

Output:

Factorial of 20 is 2432902008176640000

Explanation:
This example calculates the factorial of a given number using recursion with Long values.

Example 2: Checking if a Number is Prime

This example demonstrates checking if a number is prime using Long.

fun isPrime(n: Long): Boolean {
    if (n <= 1L) return false
    for (i in 2..n / 2) {
        if (n % i == 0L) return false
    }
    return true
}

fun main() {
    val num = 15485863L
    if (isPrime(num)) {
        println("$num is a prime number")
    } else {
        println("$num is not a prime number")
    }
}

Output:

15485863 is a prime number

Explanation:
This example checks if a given number is prime by checking divisibility from 2 to half of the number using Long values.

Example 3: Calculating Power of a Number

This example demonstrates calculating the power of a number using Long.

fun power(base: Long, exponent: Long): Long {
    if (exponent == 0L) return 1L
    var result = 1L
    for (i in 1..exponent) {
        result *= base
    }
    return result
}

fun main() {
    val base = 5L
    val exponent = 3L
    val result = power(base, exponent)
    println("$base^$exponent is $result")
}

Output:

5^3 is 125

Explanation:
This example calculates the power of a number using a loop with Long values.

6. Real-World Use Case: Calculating Compound Interest

In a real-world scenario, you might need to calculate the compound interest for an investment using Long.

Example: Calculating Compound Interest

fun calculateCompoundInterest(principal: Long, rate: Float, time: Long, n: Long): Long {
    val r = rate / 100
    val amount = principal * Math.pow((1 + r / n).toDouble(), (n * time).toDouble())
    return amount.toLong()
}

fun main() {
    val principal = 1000000L // Principal amount in rupees
    val rate = 8.0f // Annual interest rate in percentage
    val time = 10L // Investment period in years
    val n = 4L // Compounding frequency (quarterly)

    val compoundInterest = calculateCompoundInterest(principal, rate, time, n)
    println("Compound Interest: ?$compoundInterest")
}

Output:

Compound Interest: ?2219640

Explanation:
This example calculates the compound interest for an investment given the principal amount, annual interest rate, investment period, and compounding frequency using Long values.

Conclusion

The Long class in Kotlin provides a way to work with 64-bit signed integer values and perform various operations on them. It offers a range of functions to convert between different numeric types, compare values, and perform arithmetic operations. Understanding how to use the Long class and its functions is essential for effective Kotlin programming, especially when dealing with large numerical values and calculations.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare