Translate C++ to Java

Convert C++ code to Java while preserving functionality

You can query a model directly and test the results returned when using different parameter values with the Cloud console, or by calling the Vertex AI API directly.

System instructions

You are a skilled programmer knowledgeable in Java and C++, focusing on code translation between these two languages. You explain your conversion process and ensure that the translated code remains true to the original unless specified otherwise.

Prompt Freeform

Please convert the following C++ code to Java. Implement the equivalent of C++'s isPrime function using Java's BigInteger class for prime checking.

#include <iostream>
#include <string>
#include <cmath>

using namespace std;

bool isPrime(long long number) {
  if (number <= 1) return false;
  if (number == 2) return true;
  if (number % 2 == 0) return false;
  for (long long i = 3; i <= sqrt(number); i += 2) {
    if (number % i == 0) return false;
  }
  return true;
}

int main() {
  string largeNumber;
  cout << "Enter a large number: ";
  cin >> largeNumber;

  int primeSubstringCount = 0;

  for (size_t i = 0; i < largeNumber.length(); ++i) {
    for (size_t j = i + 1; j <= largeNumber.length(); ++j) {
      string substring = largeNumber.substr(i, j - i);
      long long number = stoll(substring);

      if (isPrime(number)) {
        primeSubstringCount++;
        cout << "Prime substring: " << substring << endl;
      }
    }
  }

  cout << "Total number of prime substrings: " << primeSubstringCount << endl;

  return 0;
}

Response

The C++ code efficiently checks for prime substrings within a large number. Translating this to Java requires careful consideration of data types to handle potentially very large numbers. We'll use BigInteger for this purpose. Here's the Java equivalent:

import java.math.BigInteger;
import java.util.Scanner;

public class PrimeSubstrings {

    public static boolean isPrime(BigInteger number) {
        if (number.compareTo(BigInteger.ONE) <= 0) return false;
        if (number.equals(BigInteger.valueOf(2))) return true;
        if (number.mod(BigInteger.valueOf(2)).equals(BigInteger.ZERO)) return false;
        for (BigInteger i = BigInteger.valueOf(3); i.compareTo(number.sqrt()) <= 0; i = i.add(BigInteger.valueOf(2))) {
            if (number.mod(i).equals(BigInteger.ZERO)) return false;
        }
        return true;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a large number: ");
        String largeNumber = scanner.nextLine();

        int primeSubstringCount = 0;

        for (int i = 0; i < largeNumber.length(); ++i) {
            for (int j = i + 1; j <= largeNumber.length(); ++j) {
                String substring = largeNumber.substring(i, j);
                BigInteger number = new BigInteger(substring);

                if (isPrime(number)) {
                    primeSubstringCount++;
                    System.out.println("Prime substring: " << substring);
                }
            }
        }

        System.out.println("Total number of prime substrings: " + primeSubstringCount);
        scanner.close();
    }
}

Conversion Process Explanation:

  1. Headers and Namespaces: The C++ #include directives are replaced with Java import statements. The using namespace std; is not needed in Java; we explicitly use the fully qualified names (e.g., BigInteger.valueOf(2)).

  2. Data Types: The crucial change is using BigInteger in Java to replace long long. This allows us to handle arbitrarily large numbers without overflow issues, mirroring the C++ code's ability to process large inputs.

  3. isPrime Function: The logic of the isPrime function is largely preserved. The key differences are:

    • Comparisons: Instead of <=, ==, and %, we use compareTo(), equals(), and mod() methods of the BigInteger class.
    • Square Root: We use number.sqrt() to efficiently calculate the square root for the loop's upper bound.
  4. String Manipulation: C++'s substr is directly equivalent to Java's substring.

  5. Input/Output: C++'s cout and cin are replaced with Java's System.out.print and Scanner class, respectively. Remember to close the Scanner to release resources.

  6. Error Handling: The Java code implicitly handles potential NumberFormatException if the input string is not a valid number. More robust error handling could be added if needed.

This Java code provides a functionally equivalent solution to the given C++ code, handling large numbers effectively using BigInteger. The core algorithm remains unchanged, ensuring the translation is faithful to the original intent.

Model: gemini-1.5-flash-002
Temperature: 0.2
Max output tokens: 8192
TopK: 40.0
TopP: 0.95