/******************************************************************************
* Compilation: javac Polynomial.java
* Execution: java Polynomial
*
* Polynomials with integer coefficients.
*
* % java Polynomial
* zero(x) = 0
* p(x) = 4x^3 + 3x^2 + 2x + 1
* q(x) = 3x^2 + 5
* p(x) + q(x) = 4x^3 + 6x^2 + 2x + 6
* p(x) * q(x) = 12x^5 + 9x^4 + 26x^3 + 18x^2 + 10x + 5
* p(q(x)) = 108x^6 + 567x^4 + 996x^2 + 586
* p(x) - p(x) = 0
* 0 - p(x) = -4x^3 - 3x^2 - 2x - 1
* p(3) = 142
* p'(x) = 12x^2 + 6x + 2
* p''(x) = 24x + 6
*
******************************************************************************/ package edu.princeton.cs.algs4; /**
* The {@code Polynomial} class represents a polynomial with integer
* coefficients.
* Polynomials are immutable: their values cannot be changed after they
* are created.
* It includes methods for addition, subtraction, multiplication, composition,
* differentiation, and evaluation.
* <p>
* For additional documentation,
* see <a href="https://algs4.cs.princeton.edu/99scientific">Section 9.9</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class Polynomial {
private int[] coef; // coefficients p(x) = sum { coef[i] * x^i }
private int degree; // degree of polynomial (-1 for the zero polynomial) /**
* Initializes a new polynomial a x^b
* @param a the leading coefficient
* @param b the exponent
* @throws IllegalArgumentException if {@code b} is negative
*/
public Polynomial(int a, int b) {
if (b < 0) {
throw new IllegalArgumentException("exponent cannot be negative: " + b);
}
coef = new int[b+1];
coef[b] = a;
reduce();
} // pre-compute the degree of the polynomial, in case of leading zero coefficients
// (that is, the length of the array need not relate to the degree of the polynomial)
private void reduce() {
degree = -1;
for (int i = coef.length - 1; i >= 0; i--) {
if (coef[i] != 0) {
degree = i;
return;
}
}
} /**
* Returns the degree of this polynomial.
* @return the degree of this polynomial, -1 for the zero polynomial.
*/
public int degree() {
return degree;
} /**
* Returns the sum of this polynomial and the specified polynomial.
*
* @param that the other polynomial
* @return the polynomial whose value is {@code (this(x) + that(x))}
*/
public Polynomial plus(Polynomial that) {
Polynomial poly = new Polynomial(0, Math.max(this.degree, that.degree));
for (int i = 0; i <= this.degree; i++) poly.coef[i] += this.coef[i];
for (int i = 0; i <= that.degree; i++) poly.coef[i] += that.coef[i];
poly.reduce();
return poly;
} /**
* Returns the result of subtracting the specified polynomial
* from this polynomial.
*
* @param that the other polynomial
* @return the polynomial whose value is {@code (this(x) - that(x))}
*/
public Polynomial minus(Polynomial that) {
Polynomial poly = new Polynomial(0, Math.max(this.degree, that.degree));
for (int i = 0; i <= this.degree; i++) poly.coef[i] += this.coef[i];
for (int i = 0; i <= that.degree; i++) poly.coef[i] -= that.coef[i];
poly.reduce();
return poly;
} /**
* Returns the product of this polynomial and the specified polynomial.
* Takes time proportional to the product of the degrees.
* (Faster algorithms are known, e.g., via FFT.)
*
* @param that the other polynomial
* @return the polynomial whose value is {@code (this(x) * that(x))}
*/
public Polynomial times(Polynomial that) {
Polynomial poly = new Polynomial(0, this.degree + that.degree);
for (int i = 0; i <= this.degree; i++)
for (int j = 0; j <= that.degree; j++)
poly.coef[i+j] += (this.coef[i] * that.coef[j]);
poly.reduce();
return poly;
} /**
* Returns the composition of this polynomial and the specified
* polynomial.
* Takes time proportional to the product of the degrees.
* (Faster algorithms are known, e.g., via FFT.)
*
* @param that the other polynomial
* @return the polynomial whose value is {@code (this(that(x)))}
*/
public Polynomial compose(Polynomial that) {
Polynomial poly = new Polynomial(0, 0);
for (int i = this.degree; i >= 0; i--) {
Polynomial term = new Polynomial(this.coef[i], 0);
poly = term.plus(that.times(poly));
}
return poly;
} /**
* Compares this polynomial to the specified polynomial.
*
* @param other the other polynoimal
* @return {@code true} if this polynomial equals {@code other};
* {@code false} otherwise
*/
@Override
public boolean equals(Object other) {
if (other == this) return true;
if (other == null) return false;
if (other.getClass() != this.getClass()) return false;
Polynomial that = (Polynomial) other;
if (this.degree != that.degree) return false;
for (int i = this.degree; i >= 0; i--)
if (this.coef[i] != that.coef[i]) return false;
return true;
} /**
* Returns the result of differentiating this polynomial.
*
* @return the polynomial whose value is {@code this'(x)}
*/
public Polynomial differentiate() {
if (degree == 0) return new Polynomial(0, 0);
Polynomial poly = new Polynomial(0, degree - 1);
poly.degree = degree - 1;
for (int i = 0; i < degree; i++)
poly.coef[i] = (i + 1) * coef[i + 1];
return poly;
} /**
* Returns the result of evaluating this polynomial at the point x.
*
* @param x the point at which to evaluate the polynomial
* @return the integer whose value is {@code (this(x))}
*/
public int evaluate(int x) {
int p = 0;
for (int i = degree; i >= 0; i--)
p = coef[i] + (x * p);
return p;
} /**
* Compares two polynomials by degree, breaking ties by coefficient of leading term.
*
* @param that the other point
* @return the value {@code 0} if this polynomial is equal to the argument
* polynomial (precisely when {@code equals()} returns {@code true});
* a negative integer if this polynomialt is less than the argument
* polynomial; and a positive integer if this polynomial is greater than the
* argument point
*/
public int compareTo(Polynomial that) {
if (this.degree < that.degree) return -1;
if (this.degree > that.degree) return +1;
for (int i = this.degree; i >= 0; i--) {
if (this.coef[i] < that.coef[i]) return -1;
if (this.coef[i] > that.coef[i]) return +1;
}
return 0;
} /**
* Return a string representation of this polynomial.
* @return a string representation of this polynomial in the format
* 4x^5 - 3x^2 + 11x + 5
*/
@Override
public String toString() {
if (degree == -1) return "0";
else if (degree == 0) return "" + coef[0];
else if (degree == 1) return coef[1] + "x + " + coef[0];
String s = coef[degree] + "x^" + degree;
for (int i = degree - 1; i >= 0; i--) {
if (coef[i] == 0) continue;
else if (coef[i] > 0) s = s + " + " + (coef[i]);
else if (coef[i] < 0) s = s + " - " + (-coef[i]);
if (i == 1) s = s + "x";
else if (i > 1) s = s + "x^" + i;
}
return s;
} /**
* Unit tests the polynomial data type.
*
* @param args the command-line arguments (none)
*/
public static void main(String[] args) {
Polynomial zero = new Polynomial(0, 0); Polynomial p1 = new Polynomial(4, 3);
Polynomial p2 = new Polynomial(3, 2);
Polynomial p3 = new Polynomial(1, 0);
Polynomial p4 = new Polynomial(2, 1);
Polynomial p = p1.plus(p2).plus(p3).plus(p4); // 4x^3 + 3x^2 + 1 Polynomial q1 = new Polynomial(3, 2);
Polynomial q2 = new Polynomial(5, 0);
Polynomial q = q1.plus(q2); // 3x^2 + 5 Polynomial r = p.plus(q);
Polynomial s = p.times(q);
Polynomial t = p.compose(q);
Polynomial u = p.minus(p); StdOut.println("zero(x) = " + zero);
StdOut.println("p(x) = " + p);
StdOut.println("q(x) = " + q);
StdOut.println("p(x) + q(x) = " + r);
StdOut.println("p(x) * q(x) = " + s);
StdOut.println("p(q(x)) = " + t);
StdOut.println("p(x) - p(x) = " + u);
StdOut.println("0 - p(x) = " + zero.minus(p));
StdOut.println("p(3) = " + p.evaluate(3));
StdOut.println("p'(x) = " + p.differentiate());
StdOut.println("p''(x) = " + p.differentiate().differentiate());
}
} /******************************************************************************
* Copyright 2002-2018, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/

java 多项式的更多相关文章

  1. Spark案例分析

    一.需求:计算网页访问量前三名 import org.apache.spark.rdd.RDD import org.apache.spark.{SparkConf, SparkContext} /* ...

  2. JAVA入门 第五周 1多项式

    1 多项式加法(5分) 题目内容: 一个多项式可以表达为x的各次幂与系数乘积的和,比如: 现在,你的程序要读入两个多项式,然后输出这两个多项式的和,也就是把对应的幂上的系数相加然后输出. 程序要处理的 ...

  3. 最小二乘法多项式拟合的Java实现

    背景 由项目中需要根据一些已有数据学习出一个y=ax+b的一元二项式,给定了x,y的一些样本数据,通过梯度下降或最小二乘法做多项式拟合得到a.b,解决该问题时,首先想到的是通过spark mllib去 ...

  4. Java 一维多项式计算

    求解Java一维多项式的通用方法 比如ax^4+bx^3+cx^2+dx+e 可以化为(((ax+b)x+c)x+d)x+e 那么观察规律可以将系数放到一个数组里num[e,d,c,b,a] publ ...

  5. 【Java例题】5.1 多项式计算

    1. 计算下列多项式的值. pn=an*x^n+...+a1*x+a0其中,"^"表示乘方. x.n以及ai(i=0,1,...,n-1)由键盘输入. package chapte ...

  6. 中国MOOC_零基础学Java语言_第5周 数组_1多项式加法

    第5周编程题 查看帮助 返回   第5周编程题 依照学术诚信条款,我保证此作业是本人独立完成的. 温馨提示: 1.本次作业属于Online Judge题目,提交后由系统即时判分. 2.学生可以在作业截 ...

  7. Java练习 SDUT-2504_多项式求和

    多项式求和 Time Limit: 1000 ms Memory Limit: 65536 KiB Problem Description 多项式描述如下: 1 - 1/2 + 1/3 - 1/4 + ...

  8. Java实现 洛谷 多项式输出

    题目描述 一元nn次多项式可用如下的表达式表示: 其中,a_ix^ia i ​ x i 称为ii次项,a_ia i ​ 称为ii次项的系数.给出一个一元多项式各项的次数和系数,请按照如下规定的格式要求 ...

  9. Java实现 蓝桥杯VIP 算法提高 棋盘多项式

      算法提高 棋盘多项式   时间限制:1.0s   内存限制:256.0MB 棋盘多项式 问题描述 八皇后问题是在棋盘上放皇后,互相不攻击,求方案.变换一下棋子,还可以有八车问题,八马问题,八兵问题 ...

随机推荐

  1. git 强制取消本地修改

    本地的项目中修改不做保存操作,可以用到Git pull的强制覆盖,具体代码如下: git fetch --allgit reset --hard origin/master git fetch 指令是 ...

  2. JS:面向对象(基础篇)

    面向对象(Object-Oriented,OO)的语言有一个标志,那就是它们都有类的概念.long long ago,js是没有类的概念(ES6推出了class,但其原理还是基于原型),但是它是基于原 ...

  3. DNF邀请码开发再开发方案需求

    一.原因分析:   1.现实原因:主播粉丝量级有限,一定规模粉丝注册消耗完后无法进 行之后合作 2.主播资源有限,能合作主播数量少   3.直播粉丝真实接近核心用户,但是不能将其有效转化为平台流水   ...

  4. <python练习题>python练习题(常练勿忘)

    学了python,去面试经常出现,某个或某些库不熟悉导则想不起来怎么写,知道思路而写不出来,多半还是不够熟悉,这里就作为熟悉python的地方,多做做题,多思考. 题目1:店铺ID为00000000- ...

  5. mongo数组修改器—$push、$ne、$addtoset、$pop、$pull

    这几个方法也很有意思 $push 像已有的数组末尾加入一个元素,要是元素不存在,就会创建一个新的元素,如果元素存在了,就会再添加一个一模一样的元素,会造成元素的重复,所以在使用的时候,要确保该元素不存 ...

  6. Oracle之视图联合查询加排序问题

    在公司修改bug,有这样的需求:需要从两张视图中查出相同字段的数据,按照导师姓名先排序,再按照学号排序 union联合两张表,SELECT * from((SELECT DS_ID,PYLX_ID,Y ...

  7. Python学习笔记(九)——字符串

    # 5.1 字符串的拼接 str1 = '我今天一共走了' num = 1280 str2 = '步' print(str1+str(num)+str2) # 计算字符串长度 print(len(st ...

  8. django 模型ManyToMany 关联的添加,删除,查询

    models.py文件内容: from django.db import models class person(models.Model): name = CharField(max_length= ...

  9. JAVA单线程和多线程的实现方式

    1.java单线程的实现          一个任务一个人独立完成 public class SingletonThread { @SuppressWarnings("static-acce ...

  10. javascript中内置函数

    一.基本函数库 split():用于把一个字符串分割成字符串数组 toUpperCase(): substr(): 长度 length() 拼接(两种) + concat():合并多个字符串,并返回合 ...