Stay organized with collections
Save and categorize content based on your preferences.
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.
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.
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:
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)).
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.
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.
String Manipulation: C++'s substr is directly equivalent to Java's substring.
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.
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.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2024-11-18 UTC."],[],[]]