Перепиши код на язык java 
import sympy as sp
import itertools


def is_prime(num):
    if num < 2:
        return False
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            return False
    return True

def normalize_coefficients(poly, p):
    normalized = [(coeff % p + p) % p for coeff in poly.all_coeffs()]
    return sp.Poly(normalized, poly.gens, modulus=p)

def poly_to_str(poly, p):
    coeffs = [(int(coeff) % p + p) % p for coeff in poly.all_coeffs()]
    terms = []
    for i, coeff in enumerate(reversed(coeffs)):
        if coeff != 0:
            if i == 0:
                terms.append(f"{coeff}")
            elif i == 1:
                terms.append(f"{coeff}*x")
            else:
                terms.append(f"{coeff}*x**{i}")
    return " + ".join(terms) if terms else "0"


def generate_irreducible_poly(p, r):
    x = sp.symbols('x')
    possible_polys = itertools.product(range(p), repeat=r + 1)

    for coeffs in possible_polys:
        if coeffs[0] == 0:
            continue
        poly = sp.Poly(sum(c * x**i for i, c in enumerate(reversed(coeffs))), x, modulus=p)
        poly = normalize_coefficients(poly, p)
        if poly.is_irreducible:
            return poly
    return None


def create_field(p, r):
    x = sp.symbols('x')
    modulus_poly = generate_irreducible_poly(p, r)
    if not modulus_poly:
        raise ValueError(f"Не найден неприводимый многочлен {r} степени над Z_{p}.")

    elements = []
    for coeffs in itertools.product(range(p), repeat=r):
        poly = sp.Poly(sum(c * x**i for i, c in enumerate(coeffs)), x, modulus=p)
        poly = normalize_coefficients(poly, p)
        elements.append(poly)

    return modulus_poly, elements


def mod_multiply(poly1, poly2, modulus_poly, p):
    x = sp.symbols('x')
    result = sp.Poly(poly1 * poly2, x, modulus=p)
    result = result.div(modulus_poly)[1]
    return normalize_coefficients(result, p)


def find_generators(elements, modulus_poly, p):
    x = sp.symbols('x')
    zero = sp.Poly(0, x, modulus=p)

    non_zero_elements = [el for el in elements if el != zero]
    group_order = len(non_zero_elements)

    generators = []

    for candidate in non_zero_elements:
        seen = set()
        current = sp.Poly(1, x, modulus=p)
        for _ in range(group_order):
            current = mod_multiply(current, candidate, modulus_poly, p)
            seen.add(tuple(normalize_coefficients(current, p).all_coeffs()))
        if len(seen) == group_order:
            generators.append(candidate)

    return non_zero_elements, generators


def display_results(p, r, modulus_poly, elements, group_elements, generators):
    print(f"Построение поля GF({p}^{r}):")
    print(f"Выбран неприводимый многочлен: {poly_to_str(modulus_poly, p)}")
    print("\nПоле содержит следующие элементы:")
    for i, elem in enumerate(elements):
        print(f"  {i}: {poly_to_str(elem, p)}")

    print("\nМультипликативная группа:")
    for i, elem in enumerate(group_elements):
        print(f"  {i + 1}: {poly_to_str(elem, p)}")

    print("\nПорождающие элементы мультипликативной группы:")
    for generator in generators:
        print(f"\nПорождающий элемент: {poly_to_str(generator, p)}")
        print("Возведение в степени:")
        current = sp.Poly(1, generator.gen, modulus=p)
        for power in range(1, len(group_elements) + 1):
            current = mod_multiply(current, generator, modulus_poly, p)
            print(f"  ({poly_to_str(generator, p)})^{power} = {poly_to_str(current, p)}")


def main():
    print("Построение конечного поля GF(p^k) и нахождение порождающих элементов мультипликативной группы.")

    try:
        p = int(input("Введите простое число p - порядок поля: "))
        if not is_prime(p):
            print("p должно быть простым числом. Введите другое число.")
            return

        r = int(input("Введите степень расширения r: "))
        if r <= 0:
            print("r должно быть положительным числом. Введите другое число.")
            return

        modulus_poly, elements = create_field(p, r)

        group_elements, generators = find_generators(elements, modulus_poly, p)

        display_results(p, r, modulus_poly, elements, group_elements, generators)

    except ValueError as e:
        print(f"Ошибка: {e}")


if __name__ == "__main__":
    main()