У меня есть программа на java, однако она работает некорректно, так как для входных…
- User
У меня есть программа на java, однако она работает некорректно, так как для входных данных: 3 3 1 0 2 2 4, она выводит что нет корней данной степени, однако корни данной степени существуют. Исправь программу: package FiniteFieldRootsFinder;
import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Scanner;
public class FiniteFieldRootsFinder {
static class Polynomial { private final int[] coefficients; public Polynomial(int[] coefficients) { int m = coefficients.length - 1; while (m > 0 && coefficients[m] == 0) { m--; } this.coefficients = new int[m + 1]; System.arraycopy(coefficients, 0, this.coefficients, 0, m + 1); } public int degree() { return coefficients.length - 1; } public int getCoefficient(int k) { if (k < 0 || k >= coefficients.length) { return 0; } return coefficients[k]; } public Polynomial[] divide(Polynomial divisor, int p) { int[] dividend = this.coefficients.clone(); int[] divisorCoeffs = divisor.coefficients; int divisorDegree = divisor.degree(); int[] quotient = new int[Math.max(0, this.degree() - divisor.degree() + 1)]; while (dividend.length - 1 >= divisorDegree && !isZero(dividend)) { int leadCoeffDividend = dividend[dividend.length - 1]; int leadCoeffDivisor = divisorCoeffs[divisorDegree]; if (leadCoeffDivisor == 0) { break; } int factor = multiplyInverse(leadCoeffDivisor, p); if (factor == -1) { break; } factor = (leadCoeffDividend * factor) % p; quotient[quotient.length - (dividend.length - divisorDegree)] = factor; for (int i = 0; i <= divisorDegree; i++) { int index = dividend.length - 1 - i; dividend[index] = (dividend[index] - factor * divisorCoeffs[divisorDegree - i]) % p; if (dividend[index] < 0) { dividend[index] += p; } } while (dividend.length > 0 && dividend[dividend.length - 1] == 0) { dividend = java.util.Arrays.copyOf(dividend, dividend.length - 1); } if (dividend.length == 0) { dividend = new int[]{0}; } } Polynomial quotientPoly = new Polynomial(quotient); Polynomial remainderPoly = new Polynomial(dividend); return new Polynomial[]{quotientPoly, remainderPoly}; } private boolean isZero(int[] coeffs) { for (int c : coeffs) { if (c != 0) return false; } return true; } public boolean divides(Polynomial divisor, int p) { Polynomial[] result = this.divide(divisor, p); return result[1].isZero(); } public boolean isZero() { for (int c : coefficients) { if (c != 0) return false; } return true; } private int multiplyInverse(int a, int p) { a = a % p; for (int i = 1; i < p; i++) { if ((a * i) % p == 1) { return i; } } return -1; } public boolean isIrreducible(int p) { if (this.degree() < 1) return false; if (this.degree() == 1) return true; int halfDegree = this.degree() / 2; for (int d = 1; d <= halfDegree; d++) { List<Polynomial> irreducibleDivisors = generateIrreduciblePolynomials(d, p); for (Polynomial divisor : irreducibleDivisors) { if (this.divides(divisor, p)) { return false; } } } return true; } private List<Polynomial> generateIrreduciblePolynomials(int deg, int p) { List<Polynomial> irreducibles = new ArrayList<>(); generateIrreduciblePolynomialsHelper(new int[deg + 1], deg, p, irreducibles, 0); return irreducibles; } private void generateIrreduciblePolynomialsHelper(int[] coeffs, int deg, int p, List<Polynomial> irreducibles, int index) { if (index > deg) { Polynomial poly = new Polynomial(coeffs); if (poly.isIrreducible(p)) { irreducibles.add(poly); } return; } for (int i = 0; i < p; i++) { coeffs[index] = i; generateIrreduciblePolynomialsHelper(coeffs, deg, p, irreducibles, index + 1); } } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (int i = coefficients.length - 1; i >= 0; i--) { if (coefficients[i] != 0) { if (sb.length() > 0) { sb.append(" + "); } if (i == 0) { sb.append(coefficients[i]); } else if (i == 1) { if (coefficients[i] != 1) sb.append(coefficients[i]); sb.append("z"); } else { if (coefficients[i] != 1) sb.append(coefficients[i]); sb.append("z^").append(i); } } } if (sb.length() == 0) { return "0"; } return sb.toString(); } } static class FieldElement { private final int[] coefficients; private static int p; private static int n; private static Polynomial irreduciblePoly; public static void initialize(int prime, int degree, Polynomial irreduciblePoly) { p = prime; n = degree; FieldElement.irreduciblePoly = irreduciblePoly; } public FieldElement(int[] coefficients) { this.coefficients = new int[n]; for (int i = 0; i < n; i++) { if (i < coefficients.length) { this.coefficients[i] = mod(coefficients[i]); } else { this.coefficients[i] = 0; } } } private int mod(int a) { int res = a % p; if (res < 0) res += p; return res; } public FieldElement add(FieldElement other) { int[] result = new int[n]; for (int i = 0; i < n; i++) { result[i] = mod(this.coefficients[i] + other.coefficients[i]); } return new FieldElement(result); } public FieldElement multiply(FieldElement other) { int[] temp = new int[2 * n - 1]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { temp[i + j] = (temp[i + j] + this.coefficients[i] * other.coefficients[j]) % p; } } for (int i = temp.length - 1; i >= n; i--) { if (temp[i] != 0) { int factor = temp[i]; for (int j = 0; j < irreduciblePoly.coefficients.length; j++) { temp[i - n + j] = (temp[i - n + j] - factor * irreduciblePoly.getCoefficient(j)) % p; if (temp[i - n + j] < 0) temp[i - n + j] += p; } temp[i] = 0; } } int[] result = new int[n]; for (int i = 0; i < n; i++) { result[i] = temp[i] % p; if (result[i] < 0) result[i] += p; } return new FieldElement(result); } public FieldElement pow(int exponent) { FieldElement result = FiniteFieldRootsFinder.getOne(); FieldElement base = this; int exp = exponent; while (exp > 0) { if ((exp & 1) == 1) { result = result.multiply(base); } base = base.multiply(base); exp >>= 1; } return result; } public boolean isOne() { return (this.coefficients[0] == 1) && isZeroOtherCoefficients(); } public boolean isZero() { for (int i = 0; i < coefficients.length; i++) { if (coefficients[i] != 0) return false; } return true; } private boolean isZeroOtherCoefficients() { for (int i = 1; i < coefficients.length; i++) { if (coefficients[i] != 0) return false; } return true; } @Override public boolean equals(Object obj) { if (!(obj instanceof FieldElement)) { return false; } FieldElement other = (FieldElement) obj; for (int i = 0; i < n; i++) { if (this.coefficients[i] != other.coefficients[i]) return false; } return true; } @Override public int hashCode() { return Objects.hash(coefficients); } @Override public String toString() { StringBuilder sb = new StringBuilder(); boolean first = true; for (int i = n - 1; i >= 0; i--) { if (coefficients[i] != 0) { if (!first) { sb.append(" + "); } if (i == 0) { sb.append(coefficients[i]); } else if (i == 1) { if (coefficients[i] != 1) sb.append(coefficients[i]); sb.append("z"); } else { if (coefficients[i] != 1) sb.append(coefficients[i]); sb.append("z^").append(i); } first = false; } } if (sb.length() == 0) { return "0"; } return sb.toString(); } public int[] getCoefficients() { return coefficients; } } static class FiniteField { private final int p; private final int n; private final Polynomial irreduciblePoly; private final List<FieldElement> elements; public FiniteField(int p, int n, Polynomial irreduciblePoly) { this.p = p; this.n = n; this.irreduciblePoly = irreduciblePoly; this.elements = generateElements(); } private List<FieldElement> generateElements() { List<FieldElement> elems = new ArrayList<>(); int total = (int) Math.pow(p, n); for (int i = 0; i < total; i++) { int[] coeffs = new int[n]; int num = i; for (int j = 0; j < n; j++) { coeffs[j] = num % p; num /= p; } elems.add(new FieldElement(coeffs)); } return elems; } public boolean isIrreducible() { return irreduciblePoly.isIrreducible(p); } public List<FieldElement> getElements() { return elements; } public FieldElement getOne() { int[] one = new int[n]; one[0] = 1; return new FieldElement(one); } public Polynomial getIrreduciblePoly() { return irreduciblePoly; } } private static FieldElement oneElement; public static FieldElement getOne() { return oneElement; } public static void setOne(FieldElement elem) { oneElement = elem; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); try { System.out.print("Введите простое число p (характеристика поля GF(p^n)): "); int p = scanner.nextInt(); if (p <= 1) { System.out.println("Ошибка: p должно быть простым числом больше 1."); return; } if (!isPrime(p)) { System.out.println("Ошибка: Введенное число p не является простым."); return; } System.out.print("Введите степень расширения n (так что GF(p^n)): "); int n = scanner.nextInt(); if (n < 1) { System.out.println("Ошибка: Степень расширения n должна быть натуральным числом (n >= 1)."); return; } System.out.println("Введите коэффициенты неприводимого многочлена f(z) = z^n + a_(n-1)z^(n-1) + ... + a0, начиная с старшей степени:"); int[] fCoeffs = new int[n + 1]; for (int i = n; i >= 0; i--) { System.out.print("Коэффициент при z^" + i + ": "); fCoeffs[i] = scanner.nextInt(); fCoeffs[i] %= p; if (fCoeffs[i] < 0) fCoeffs[i] += p; } Polynomial irreduciblePoly = new Polynomial(fCoeffs); FiniteField tempField = new FiniteField(p, n, irreduciblePoly); if (!tempField.isIrreducible()) { System.out.println("Ошибка: Введенный многочлен не является неприводимым над GF(" + p + ")."); return; } FiniteField field = new FiniteField(p, n, irreduciblePoly); FieldElement.initialize(p, n, field.getIrreduciblePoly()); setOne(field.getOne()); System.out.print("Введите степень y (для корней y-й степени): "); int y = scanner.nextInt(); if (y < 1) { System.out.println("Ошибка: Степень y должна быть натуральным числом (y >= 1)."); return; } List<FieldElement> elements = field.getElements(); List<FieldElement> roots = new ArrayList<>(); for (FieldElement elem : elements) { if (elem.isZero()) { continue; } FieldElement power = elem.pow(y); if (power.equals(oneElement)) { roots.add(elem); } } System.out.println("\nЭлементы поля GF(" + p + "^" + n + "), удовлетворяющие условию α^" + y + " = 1:"); if (roots.isEmpty()) { System.out.println("Нет корней степени " + y + " в данном поле."); } else { for (FieldElement root : roots) { System.out.println(root); } } } catch (Exception e) { System.out.println("Произошла ошибка при вводе данных. Убедитесь, что вводите корректные значения."); System.out.println("Описание ошибки: " + e.getMessage()); } finally { scanner.close(); } } private static boolean isPrime(int num) { if (num <= 1) return false; if (num == 2) return true; if (num % 2 == 0) return false; int sqrt = (int) Math.sqrt(num); for (int i = 3; i <= sqrt; i += 2) { if (num % i == 0) return false; } return true; } - Assistant