# 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. - For an example of using the Vertex AI API, see [Quickstart using the Vertex AI API](https://docs.cloud.google.com/vertex-ai/generative-ai/docs/start/quickstarts/api-quickstart). - To view this sample in the Cloud console: [Go to Google Cloud console](https://console.cloud.google.com/vertex-ai/generative/language/prompt-examples/Translate%20C++%20to%20Java) <br /> ||
| |---| | **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 Of course. Here is the Java equivalent of the provided C++ code, along with a detailed explanation of the translation process. ### Java Equivalent Code The Java code uses the `BigInteger` class for robust primality testing, as requested. import java.math.BigInteger; import java.util.Scanner; public class PrimeSubstringFinder { /** * Checks if a number, given as a string, is prime using BigInteger. * * @param numberStr The string representation of the number to check. * @return true if the number is probably prime, false otherwise. */ public static boolean isPrime(String numberStr) { // Create a BigInteger object from the string representation of the number. BigInteger number = new BigInteger(numberStr); // Use the isProbablePrime method. The parameter is "certainty": // The probability that this method returns true for a composite number // is less than 1/(2^certainty). A certainty of 10-15 is generally // sufficient for most practical purposes. return number.isProbablePrime(15); } public static void main(String[] args) { // Use Scanner for console input, which is the Java equivalent of cin. Scanner scanner = new Scanner(System.in); System.out.print("Enter a large number: "); String largeNumber = scanner.nextLine(); scanner.close(); // Good practice to close the scanner to prevent resource leaks. int primeSubstringCount = 0; // Iterate through all possible start indices of a substring. for (int i = 0; i < largeNumber.length(); i++) { // Iterate through all possible end indices of a substring. for (int j = i + 1; j <= largeNumber.length(); j++) { // Extract the substring. Note the difference from C++'s substr. String substring = largeNumber.substring(i, j); // The isPrime method now directly accepts a string. if (isPrime(substring)) { primeSubstringCount++; System.out.println("Prime substring: " + substring); } } } System.out.println("Total number of prime substrings: " + primeSubstringCount); } } ### Conversion Process and Key Differences 1. **Class Structure:** Java is a strictly object-oriented language, so all code must reside within a class. I created a `PrimeSubstringFinder` class to encapsulate the program's logic. The `main` method serves as the entry point, similar to C++'s `main` function. 2. **Input Handling:** - C++ uses `iostream` with `cin` for standard input. - The standard Java equivalent is the `java.util.Scanner` class. We create an instance of `Scanner` that reads from `System.in` (the console). - `cin >> largeNumber` is replaced by `scanner.nextLine()`. - It's a best practice in Java to call `scanner.close()` when you are finished with it to release system resources. 3. **The `isPrime` Function (C++ vs. Java `BigInteger`):** - **C++ Implementation:** The original C++ code uses a trial division algorithm. It checks for divisibility by odd numbers up to the square root of the input number. This is efficient for numbers that fit within a `long long`, but it's not suitable for arbitrarily large numbers. - **Java `BigInteger` Implementation:** As requested, the Java version uses the `java.math.BigInteger` class. - `BigInteger` can represent integers of arbitrary size, limited only by available memory. This makes it perfect for the "large number" use case. - The method `isProbablePrime(int certainty)` is a highly optimized probabilistic primality test (based on Miller-Rabin). It is much faster than trial division for large numbers. - The `certainty` parameter controls the accuracy. A certainty of `15` means the probability of a composite number being incorrectly identified as prime is less than 1 in 2^15^ (1 in 32,768). This is extremely reliable for all practical purposes. - A significant advantage is that `BigInteger.isProbablePrime()` automatically handles edge cases like 0, 1, and 2 correctly, leading to cleaner code than the C++ version which required explicit checks. 4. **String Manipulation:** - This is a subtle but crucial difference. - In C++, `substr(startIndex, length)` extracts a substring starting at an index and continuing for a specific length. - In Java, `substring(beginIndex, endIndex)` extracts a substring from a beginning index up to (but **not including**) an end index. - Therefore, the C++ expression `largeNumber.substr(i, j - i)` translates directly to the Java expression `largeNumber.substring(i, j)`. 5. **Type Conversion:** - The C++ code converts each substring to a `long long` using `stoll()` before passing it to `isPrime`. - The new Java `isPrime` method is designed to accept a `String` directly. This is more robust, as it avoids a `NumberFormatException` if a substring represents a number too large to fit in Java's `long` type, and it avoids the overhead of parsing the string to a primitive type. | |---|---| | **Model:** | gemini-2.5-pro | | **Temperature:** | 0.2 | | **Max output tokens:** | 8192 | | **TopK:** | 64 | | **TopP:** | 0.95 | |