How to Find the Integral using Java

1 min read 216 words

The challenge

Create a function that finds the integral of the expression passed.

In order to find the integral all you need to do is add one to the exponent (the second argument), and divide the coefficient (the first argument) by that new number.

For example for 3x^2, the integral would be 1x^3: we added 1 to the exponent, and divided the coefficient by that new number).

Notes:

  • The output should be a string.
  • The coefficient and exponent is always a positive integer.

Examples

 3, 2  -->  "1x^3"
12, 5  -->  "2x^6"
20, 1  -->  "10x^2"
40, 3  -->  "10x^4"
90, 2  -->  "30x^3"

The solution in Java code

public class Solution {

    public static String integrate(int coefficient, int exponent) {
        int first = ++exponent;
        coefficient /= first;
        
        return coefficient+"x^"+first;
    }
  
}

A single line solution:

public class Solution {

    public static String integrate(int coefficient, int exponent) {
        return coefficient / ++exponent + "x^" + exponent;
    }
  
}

A solution using String.format():

class Solution {

    static String integrate(int coefficient, int exponent) {
        return String.format("%sx^%s", coefficient / ++exponent, exponent);
    }

}

Test cases to validate our Java solution code

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;


public class SolutionTest {
    @Test
    public void exampleTests() {
        assertEquals("1x^3", Solution.integrate(3,2));
        assertEquals("2x^6", Solution.integrate(12,5));
        assertEquals("10x^2", Solution.integrate(20,1));
        assertEquals("10x^4", Solution.integrate(40,3));
        assertEquals("30x^3", Solution.integrate(90,2));
    }
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags