Java学习笔记
XP、Win7或Ubuntu 18.04.4 LTS下的Java控制台程序
【程序1】位操作Temp.java
C:\Users\Administrator>cd c:\
c:\>javac Temp.java
c:\>java Temp
root@iZ14rcmneyrcltZ:~/cpptest/javatest# javac Temp.java
root@iZ14rcmneyrcltZ:~/cpptest/javatest# java Temp
2
7
5
-8
-1
7
==============================================================
【程序2】位操作Temp2.java
root@iZ14rcmneyrcltZ:~/cpptest/javatest# javac Temp2.java
root@iZ14rcmneyrcltZ:~/cpptest/javatest# java Temp2
ff0000
16711680
==============================================================
【程序3】求两点距离
//范数:‖x‖定义为内积的开根号,也即<x,x>^(1/2)
//范数‖x-y‖表示向量x与向量y的线段长度
//内积:满足三条性质
//内积空间:定义了内积的线性空间
c:\>javac DPoint2.java
c:\>java DPoint2
7.0710678118654755
root@iZ14rcmneyrcltZ:~/cpptest/javatest# javac DPoint2.java
root@iZ14rcmneyrcltZ:~/cpptest/javatest# java DPoint2
7.0710678118654755
==============================================================
【程序4】CZeta.java
import java.util.*;
import java.math.*;
/*
C/C++
1.644934=ζ(2)>≈1.634984
c:\>javac CZeta.java
c:\>java CZeta
请输入一个x
2
ζ(x)>≈1.6349839001848923
pi*pi/6=1.6449340672777941
*/
public class CZeta
{
//static double pi=3.141592654;
final double pi=3.141592654;
public double Zeta(double s)
{
int i;
double sum=0;
for(i=1;i<=100;i++)
{
sum+=1.0/Math.pow(i,s);
}
return sum;
}
/*
超越数e的计算
也是欧拉用e=lim[n->∞](1+1/n)^n=2.718281828459045…表示特殊的无理常数─欧拉常数
en100=2.7048138294215285
en100000=2.7182682371922975
enm100=2.7319990264290284
enm100000=2.7182954199804055
*/
public double e_n(int n)
{
double ret=Math.pow(1+(double)1/n,n);
return ret;
}
public static void main (String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("请输入一个x");
CZeta cz=new CZeta();
double x=sc.nextDouble();
double y=cz.Zeta(x);
System.out.println("ζ(x)>≈"+y);
//System.out.println("pi*pi/6="+CZeta.pi*CZeta.pi/6);
System.out.println("pi*pi/6="+cz.pi*cz.pi/6);
double en100=cz.e_n(100);
System.out.println("en100="+en100);
double en100000=cz.e_n(100000);
System.out.println("en100000="+en100000);
double enm100=cz.e_n(-100);
System.out.println("enm100="+enm100);
double enm100000=cz.e_n(-100000);
System.out.println("enm100000="+enm100000);
}
}
==============================================================
【程序5】DefiniteIntegral.java
import static java.lang.Math.*;
public class DefiniteIntegral
{
// 0~1区间n等分
private static int n = 100000;
// 随便定义个曲线e的x次方, 取其x在0~1的定积分;
public static double f(double x) {
double f;
f = pow(E, x);
return f;
}
// 梯形法求定积分
/**
* x0: 坐标下限, xn: 坐标上限
*/
public static double getDefiniteIntegralByTrapezium(double x0, double xn) {
double h = abs(xn - x0) / n;
double sum = 0;
for (double xi = 0; xi <= xn; xi = xi + h) {
sum += (f(xi) + f(xi + h)) * h / 2;
}
return sum;
}
/**
* x0: 坐标下限, xn: 坐标上限
*/
// 矩形法求定积分, 右边界
public static double getDefiniteIntegralByRectangle1(double x0, double xn) {
//h: 步长
double h = abs(xn - x0) / n;
double sum = 0;
for (double xi = 0; xi <= xn; xi = xi + h) {
sum += f(xi + h) * h;
}
return sum;
}
// 矩形法求定积分, 左边界
public static double getDefiniteIntegralByRectangle2(double x0, double xn) {
double h = abs(xn - x0) / n;
double sum = 0;
for (double xi = 0; xi <= xn; xi = xi + h) {
sum += f(xi) * h;
}
return sum;
}
/**
* 测试定积分
c:\>javac DefiniteIntegral.java
c:\>java DefiniteIntegral
1.7183090114267447
1.7183176029717737
1.7183004198816596
*/
public static void main(String[] args) {
System.out.println(getDefiniteIntegralByTrapezium(0, 1));
System.out.println(getDefiniteIntegralByRectangle1(0, 1));
System.out.println(getDefiniteIntegralByRectangle2(0, 1));
}
}
==============================================================
【程序6】Io.java
import java.io.*;
class Point
{
private int x;
private int y;
public void Put()throws IOException
{
System.out.print("x坐标为:");
BufferedReader strin=new BufferedReader(new InputStreamReader(System.in));
x=Integer.parseInt(strin.readLine());
System.out.print("y坐标为:");
y=Integer.parseInt(strin.readLine());
}
public void Get()
{
System.out.println("x坐标为:"+x);
System.out.println("y坐标为:"+y);
}
}
/*
abstract class Shape
{
abstract void Input()throws IOException;
abstract void Print()throws IOException;
}
class Line extends Shape
{
private Point point1;
private Point point2;
public void Input()throws IOException
{
System.out.println("输入直线的参数");
System.out.println("输入端点1的坐标:");
point1.Put();
System.out.println("输入端点2的坐标:");
point2.Put();
}
public void Print()throws IOException
{
System.out.println("直线的参数为");
System.out.println("端点1的坐标:");
point1.Get();
System.out.println("端点2的坐标:");
point2.Get();
}
}
*/
public class Io
{
public static void main(String[] args)throws IOException
{
Point point1=new Point();
point1.Put();
point1.Get();
/*
Line p1=new Line();
Line p2=new Line();
p1.Input();
p2.Input();
p1.Print();
p2.Print();
*/
/*
int a;
System.out.print("请输入一个整数:");
BufferedReader strin=new BufferedReader(new InputStreamReader(System.in));
a=Integer.parseInt(strin.readLine());
System.out.println("输入的数是:"+a);
Double b;
System.out.print("请输入一个double型:");
BufferedReader strin1=new BufferedReader(new InputStreamReader(System.in));
b=Double.parseDouble(strin.readLine());
System.out.println("输入的double数是:"+b);
String c;
System.out.print("请输入一个字符型:");
BufferedReader strin2=new BufferedReader(new InputStreamReader(System.in));
c=strin.readLine();
System.out.println("输入的字符是:"+c);
*/
}
}
==============================================================
【程序7】JavaPoint.java
class Point
{
private int x;
private int y;
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public Point()
{
x = 0;
y = 0;
}
public Point(int xx, int yy)
{
x = xx;
y = yy;
}
public double distance(Point p)
{
return Math.sqrt((x - p.getX()) * (x - p.getX()) + (y - p.getY())* (y - p.getY()));
}
public void Put()
{
x=10;
y=20;
}
public void Get()
{
System.out.println("x坐标为:"+x);
System.out.println("y坐标为:"+y);
}
}
class Circle
{
private Point center;
private int radius;
public Circle() { center = new Point(); radius = 0; }
public Circle(int xx, int yy, int r) { center = new Point(xx, yy); radius = r; }
public Circle(Point c, int r) { center = c; radius = r; }
public int perimeter() { return (int) (2 * Math.PI * radius); }
public double area() { return Math.PI * radius * radius; }
public int relation(Circle c)
{
int cx = c.center.getX();
int cy = c.center.getY();
int cr = c.radius;
int tx = this.center.getX();
int ty = this.center.getY();
double distance = c.center.distance(center);
if(cx == tx && cy == ty && cr == radius) { return 0; }
else if(cr == radius) { return 1; }
else if(distance <= (cr + radius)) { return 2; }
else if(distance > (cr + radius)) { return 3; }
else if(distance + c.radius <= radius) { return 4; }
return 5; }}
public class JavaPoint
{
public static void main(String[] args)
{
Point p0=new Point();
p0.Put();
p0.Get();
Point p = new Point(0, 0);
Point p1 = new Point(3, 4);
System.out.println(p.getX());
System.out.println(p.getY());
System.out.println(p.distance(p1));
Circle c = new Circle(p, 5);
Circle c1 = new Circle(0, 0, 5);
System.out.println(c.area());
System.out.println(c.perimeter());
System.out.println(c.relation(c1));
}
}
==============================================================
【程序8】JavaShape2.java
abstract class Shape
{
abstract void Input();
abstract void Print();
}
class Circle extends Shape //圆类
{
private int radius;//半径
//Point center;//圆心
public void Input()
{
radius=2;
}
public void Print()
{
System.out.println("半径:"+radius);
}
}
public class JavaShape2
{
public static void main(String[] args)
{
Circle c=new Circle();
c.Input();
c.Print();
}
}
JavaShape.java
abstract class shape
{
String name;
abstract void Area();
}
class Trangle extends shape //三角形类
{ Trangle(){}
double sideA,sideB,sideC;
boolean boo;
public Trangle(double a,double b,double c)
{
sideA=a;sideB=b;sideC=c;
this.name="三角形";
if(a+b>c&&a+c>b&&b+c>a)
{
System.out.println("我是一个三角形");
boo=true;
}
else
{
System.out.println("我不是一个三角形");
boo=false;
}
}
public void Area()
{
if(boo)
{
double p=(sideA+sideB+sideC)/2.0;
double area=Math.sqrt(p*(p-sideA)*(p-sideB)*(p-sideC));
System.out.println(name+"面积是:"+area);
}
else
{
System.out.println("不是一个三角形,不能计算面积");
}
}
public void 修改三边(double a,double b,double c)
{
sideA=a;sideB=b;sideC=c;
if(a+b>c&&a+c>b&&b+c>a)
{
boo=true;
}
else
{
boo=false;
}
}
}
class Circle extends shape //圆类
{
double r;
Circle(double r)
{
this.r=r;this.name="圆";
}
public void Area()
{
System.out.println(name+"面积是:"+3.14*r*r);
}
}
class Rectangle extends shape //矩形类
{
double a,b;
Rectangle(double a,double b)
{
this.a=a;this.b=b;this.name="矩形";
}
public void Area()
{
System.out.println(name+"面积是:"+a*b);
}
}
public class JavaShape
{
public static void main(String[] args)
{
Trangle t=new Trangle(1,2,3);
t.Area();
t.修改三边(3,4,5);
t.Area();
Circle c=new Circle(2);
c.Area();
Rectangle r=new Rectangle(4,5);
r.Area();
}
}
JavaShapeI.java
interface shape
{
final String name="图形";
void Area();
}
class Trangle implements shape
{
Trangle(){}
double sideA,sideB,sideC;
boolean boo;
public Trangle(double a,double b,double c)
{
sideA=a;sideB=b;sideC=c;
if(a+b>c&&a+c>b&&b+c>a)
{
System.out.println("我是一个三角形");
boo=true;
}
else
{
System.out.println("我不是一个三角形");
boo=false;
}
}
public void Area()
{
if(boo)
{
double p=(sideA+sideB+sideC)/2.0;
double area=Math.sqrt(p*(p-sideA)*(p-sideB)*(p-sideC));
System.out.println(name+"面积:"+area);
}
else
{
System.out.println("不是一个三角形,不能计算面积");
}
}
public void 修改三边(double a,double b,double c)
{
sideA=a;sideB=b;sideC=c;
if(a+b>c&&a+c>b&&b+c>a)
{
boo=true;
}
else
{
boo=false;
}
}
}
class Circle implements shape //圆类
{
double r;
Circle(double r)
{
this.r=r;
}
public void Area()
{
System.out.println(name+"面积是:"+3.14*r*r);
}
}
class Rectangle implements shape //矩形类
{
double a,b;
Rectangle(double a,double b)
{
this.a=a;this.b=b;
}
public void Area()
{
System.out.println(name+"面积是:"+a*b);
}
}
class A
{
public void t(shape s) //接口类型参数
{
s.Area(); //接口回调
}
}
class JavaShapeI
{
public static void main(String[] args)
{
shape s;
s=new Trangle(3,4,5);
s.Area() ; //接口回调
A a=new A();
a.t(new Circle(2));
a.t(new Rectangle(3,4));
}
}
==============================================================
【程序9】XPTest1.java
C:\>javac XPTest1.java
C:\>java XPTest1
root@iZ14rcmneyrcltZ:~/cpptest/javatest# javac XPTest1.java
root@iZ14rcmneyrcltZ:~/cpptest/javatest# java XPTest1
1
0.060000002
0.060000000000000005
0.06
0.06
==============================================================
【程序10】有理数域Q上的四则运算Q.java
C:\>javac Q.java
C:\>java Q
root@iZ14rcmneyrcltZ:~/cpptest/javatest# javac Q.java
root@iZ14rcmneyrcltZ:~/cpptest/javatest# java Q
0.06
0.04
0.0005
5
==============================================================
【程序11】MyInt.java
public class MyInt{
public int value;
public MyInt(int value){
this.value = value;
}
public static void main(String args[]){
MyInt t = new MyInt(10);
add(t);
System.out.println(t.value);
}
public static void add(MyInt temp){
temp.value += 10;
}
}
==============================================================
【程序12】ChineseCharEncodingList.java
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
public class ChineseCharEncodingList{
private static final int MIN_INDEX = 19968;
private static final int MAX_INDEX = 40869;
private static final String CR = "\r\n";
private static final String TAB = "\t";
public void execute(String fileName) throws IOException{
File f = new File(fileName);
FileWriter fw = new FileWriter(f);
fw.write("字符"+TAB+"Unicode十进制"+TAB+"Unicode十六进制"+TAB+TAB+"GBK十进制"+TAB+"GBK十六进制"+CR);
fw.write("=================================================================================="+CR);
int GBKCode;
for(int i=MIN_INDEX;i<=MAX_INDEX;i++){
GBKCode = getGBKCode(i);
fw.write((char)i+TAB+i+TAB+TAB+Integer.toHexString(i)+TAB+TAB+TAB+GBKCode+TAB+TAB+Integer.toHexString(GBKCode)+CR);
}
fw.flush();
System.out.println("Done!");
}
private int getGBKCode(int unicodeCode) throws UnsupportedEncodingException{
char c = (char) unicodeCode;
byte[] bytes = (c+"").getBytes("GBK");
return ((bytes[0]&255)<<8) + (bytes[1]&255);
}
public static void main(String[] args) throws Exception{
new ChineseCharEncodingList().execute("汉字编码一览表.txt");
}
}
==============================================================
【程序13】Constants.java
public class Constants
{
public static void main(String[] args)
{
final double CM_PER_INCH = 2.54;
double paperWidth = 8.5;
double paperHeight = 11;
System.out.println("Paper size in centimeters: "+paperWidth*CM_PER_INCH+" by "+paperHeight*CM_PER_INCH);
System.out.println("Paper size in centimeters: "+paperWidth*CM_PER_INCH_2+" by "+paperHeight*CM_PER_INCH_2);
}
public static final double CM_PER_INCH_2 = 2.54;
}
==============================================================
【程序14】Dt1.java
import java.util.Date;
public class Dt1
{
public static void main(String[] args)
{
// Get the system date/time
Date date = new Date();
System.out.println(date.getTime());
}
}
Dt2.java
import java.text.SimpleDateFormat;
import java.util.Date;
public class Dt2
{
public static void main(String[] args)
{
SimpleDateFormat bartDateFormat = new SimpleDateFormat("EEEE-MMMM-dd-yyyy");
Date date = new Date();
System.out.println(bartDateFormat.format(date));
}
}
Dt3.java
import java.text.SimpleDateFormat;
import java.util.Date;
public class Dt3
{
public static void main(String[] args)
{
// Create a date formatter that can parse dates of
// the form MM-dd-yyyy.
SimpleDateFormat bartDateFormat =new SimpleDateFormat("MM-dd-yyyy");
// Create a string containing a text date to be parsed.
String dateStringToParse = "9-29-2001";
try {
// Parse the text version of the date.
// We have to perform the parse method in a
// try-catch construct in case dateStringToParse
// does not contain a date in the format we are expecting.
Date date = bartDateFormat.parse(dateStringToParse);
// Now send the parsed date as a long value
// to the system output.
System.out.println(date.getTime());
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
Dt4.java
import java.text.DateFormat;
import java.util.Date;
public class Dt4
{
public static void main(String[] args) {
Date date = new Date();
DateFormat shortDateFormat =
DateFormat.getDateTimeInstance(
DateFormat.SHORT,
DateFormat.SHORT);
DateFormat mediumDateFormat =
DateFormat.getDateTimeInstance(
DateFormat.MEDIUM,
DateFormat.MEDIUM);
DateFormat longDateFormat =
DateFormat.getDateTimeInstance(
DateFormat.LONG,
DateFormat.LONG);
DateFormat fullDateFormat =
DateFormat.getDateTimeInstance(
DateFormat.FULL,
DateFormat.FULL);
System.out.println(shortDateFormat.format(date));
System.out.println(mediumDateFormat.format(date));
System.out.println(longDateFormat.format(date));
System.out.println(fullDateFormat.format(date));
}
}
==============================================================
【程序15】Un.java
javac Un.java
java Un
root@iZ14rcmneyrcltZ:~/cpptest/javatest# javac Un.java
Note: Un.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
root@iZ14rcmneyrcltZ:~/cpptest/javatest# java Un
φ(2)=1,模2的既约剩余类:
1
φ(4)=2,模4的既约剩余类:
1
3
φ(8)=4,模8的既约剩余类:
1
3
5
7
φ(16)=8,模16的既约剩余类:
1
3
5
7
9
11
13
15
==============================================================
【程序16】inheritanceAB.java
c:\>javac inheritanceAB.java
c:\>java inheritanceAB
root@iZ14rcmneyrcltZ:~/cpptest/javatest# javac inheritanceAB.java
root@iZ14rcmneyrcltZ:~/cpptest/javatest# java inheritanceAB
This is Func1
This is Func2
This is Func3
This is Func4
==============================================================
【程序18】Finally.java
class TestD{
private String name;
private String age;
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void info(){
System.out.println("姓名:"+name+" "+"年龄:"+age);
}
}
class Student extends TestD{
private String school;
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
public void info(){
System.out.println("姓名:"+getName()+" "+"年龄:"+getAge()+"学校:"+getSchool());
}
}
public class Finally {
public void show(TestD p){
p.info();
}
public static void main(String[] args){
TestD t = new TestD();
t.setName("林志颖");
t.setAge("33");
t.info();//父类的info()方法
Student s = new Student();
s.setName("林志颖");
s.setAge("34");
s.setSchool("华岗");
s.info();//子类的info()方法
Finally f = new Finally();
f.show(t);//这里传的是TestD类型的对象,调用的就是TestD的info()方法
f.show(s);//这里传的是子类Student的对象,调用的是子类的info()方法
//这里为java的动态绑定,注意只能传父类的或在哦类的,其它的类型不行
}
}
==============================================================
【程序19】FinallyAB.java
class A{
public void test() {
System.out.println("aaa");
}
}
class B extends A{
public void test() {
System.out.println("bbb");
}
}
public class FinallyAB {
public static void main(String[] args){
A t = new A();
t.test();
B s = new B();
s.test();
}
}
==============================================================
【程序20】Template.java
class Template<Type extends Object>{
private Type template;
public Template( ){
}
public Template( Type template){
setTemplate( template );
}
public void setTemplate( Type template){
this.template = template;
}
public Type getTemplate(){
return template;
}
public void print(){
System.out.println( template.toString());
}
public static void main(String[] args){
Template<String> stringT = new Template<String>();
stringT.setTemplate( new String( "Hello Template class" ));
stringT.print();
Template<Integer> integerT = new Template<Integer>( 5 );
integerT.print();
Template doubleT = new Template<Double>( 3.1415926 );
doubleT.print();
}
}
==============================================================
【程序21】Test.java
class Test
{
public static void main (String args[])
{
int a = 10;
int b = 2;
int c = add(a,b);
System.out.println(c);
}
public static int add(int a,int b)
{
return a+b;
}
}
Test2.java
class Parent {
public String test() {
return "Parent";
}
}
class Child extends Parent {
public String test() {
return "Child";
}
}
class Test2
{
public static void main (String args[])
{
Parent p = new Child();
String str = p.test(); //此时仍然等于 Child
System.out.println(str);
}
}
Test3.java
public class Test3
{
static int a = 27;//全局变量
static void test()
{
boolean flag = false;// flag是局部变量,他的有效范围市整个方法体
if (!flag)
{
int a = 20;// 局部变量a,是必须进行初始化的且只在if块中有效
System.out.println("a1=" + a);
}
// a = 10;
// 注意,这一行是会报编译错误:未声明变量a
}
public static void main(String[] args)
{
System.out.println("a2=" + a);
int a = 23;//局部变量
test();
System.out.println("a3=" + a);
}
}
Test4.java
public class Test4
{
public static void main(String[] args)
{
int i=10;
int j=10;
System.out.println(i==j);//对原始类型的数据比较的时候 比较的是他的值而不是地址
String s1=new String("JDK1.2");
String s2=new String("JDK1.2");
System.out.println(s1==s2);//对对象使用==比较的是引用,所以这里答案是false
String ss1=("JDK1.2");
String ss2=("JDK1.2");
System.out.println(ss1==ss2);//s1 s2是指向同1引用 编译器直接赋值的都指向 字符串标准引用区
String sss1=new String("JDK1.2");
String sss2=new String("JDK1.2");
System.out.println(sss1.intern()==sss2.intern());//因为intern()返回的是字符串标准引用区
}
}
Test5.java
class Test {
public Test (){
System.out.println("Test类的构造函数(方法)");
}
public Test(int i){
System.out.println("带参数的构造方法");
}
public Test(int i,int j){
System.out.println("带参数的构造方法");
}
}
class A{
public A(){
System.out.println("这是A的构造函数");
}
}
class Test5{
public static void main(String[] args){
A a1; //--->此时是不会打印出“这是A的构造函数”这段的
a1=new A(); //此时会打印出来
}
}
==============================================================
【程序26】A1.java
/*
c:\>javac A1.java
c:\>java A1
this is mem_func1
this is mem_vfun1
*/
public class A1
{
public int mem_data1;
public int mem_data2;
public void mem_func1(){System.out.println("this is mem_func1");this.mem_data1 =10;}
public void mem_vfun1(){System.out.println("this is mem_vfun1");this.mem_data1 =20;}
public static void main(String[] args){
A1 ptemp=new A1();
ptemp.mem_func1();
ptemp.mem_vfun1();
//this is mem_func1
//this is mem_vfun1
}
}
==============================================================
【程序27】AB.java
/*
C++
#include <iostream>
using namespace std;
class A
{
public:
void Func1(void){ cout<<"this is Func1"<<endl;};
void Func2(void){ cout<<"this is Func2"<<endl;};
};
class B : public A
{
public:
void Func3(void){ cout<<"this is Func3"<<endl;};
void Func4(void){ cout<<"this is Func4"<<endl;};
};
//继承
int main()
{
B b; // B的一个对象
b.Func1(); // B 从A 继承了函数Func1
b.Func2(); // B 从A 继承了函数Func2
b.Func3();
b.Func4();
cin.get();
return 0;
}
this is Func1
this is Func2
this is Func3
this is Func4
c:\>javac AB.java
c:\>java AB
This is Func1
This is Func2
This is Func3
This is Func4
*/
class A
{
public void Func1(){ System.out.println("This is Func1 ");}
public void Func2(){ System.out.println("This is Func2 ");}
}
class B extends A
{
public void Func3(){ System.out.println("This is Func3 ");}
public void Func4(){ System.out.println("This is Func4 ");}
}
public class AB
{
public static void main(String[] args){
B b=new B();
b.Func1();
b.Func2();
b.Func3();
b.Func4();
}
}
==============================================================
【程序28】ABC.java
/*
C++虚函数 == Java普通函数,OK
C++纯虚函数 == Java抽象函数
C++抽象类 == Java抽象类
C++虚基类 == Java接口
C++用关键字virtual来声明一个函数为虚函数,派生类的虚函数将(override)基类对应的虚函数的功能
C++
#include <iostream>
using namespace std;
class A
{
public:
virtual void Func1(void){ cout<< "This is A::Func1 \n";}
};
void Test(A *a)
{
a->Func1();
}
class B : public A
{
public:
virtual void Func1(void){ cout<< "This is B::Func1 \n";}
};
class C : public A
{
public:
virtual void Func1(void){ cout<< "This is C::Func1 \n";}
};
int main()
{
A a;
B b;
C c;
Test(&a); // 输出This is A::Func1
Test(&b); // 输出This is B::Func1
Test(&c); // 输出This is C::Func1
cin.get();
return 0;
};
This is A::Func1
This is B::Func1
This is C::Func1
c:\>javac ABC.java
c:\>java ABC
This is A::Func1
This is B::Func1
This is C::Func1
*/
class A
{
public void Func1(){ System.out.println("This is A::Func1 ");}
}
class B extends A
{
public void Func1(){ System.out.println("This is B::Func1 ");}
}
class C extends A
{
public void Func1(){ System.out.println("This is C::Func1 ");}
}
public class ABC
{
public static void Test(A a)
{
a.Func1();
}
public static void main(String[] args){
A a=new A();
B b=new B();
C c=new C();
Test(a);
Test(b);
Test(c);
//ABC.Test(a); // 输出This is A::Func1
//ABC.Test(b); // 输出This is B::Func1
//ABC.Test(c); // 输出This is C::Func1
}
}
==============================================================
【程序29】Car.java
/*
c:\>javac Car.java
c:\>java Car
This is Engine::start
This is Door::close
This is Window::rolldown
*/
class Engine{
public void start(){System.out.println("This is Engine::start ");}
public void stop(){System.out.println("This is Engine::stop ");}
}
class Door{
public void open(){System.out.println("This is Door::open ");}
public void close(){System.out.println("This is Door::close ");}
}
class Window{
public void rollup(){System.out.println("This is Window::rollup ");}
public void rolldown(){System.out.println("This is Window::rolldown ");}
}
public class Car {
private Engine engine=new Engine();
private Door door=new Door();
private Window window=new Window();
public static void main(String[] args) {
Car car=new Car();
car.engine.start();
car.door.close();
car.window.rolldown();
}
}
==============================================================
【程序30】Cartoon.java
/*
c:\>javac Cartoon.java
c:\>java Cartoon
Art ~~~``Drawing ~~~``Cartoon ~~~``
*/
class Art{
Art(){
System.out.print("Art ~~~``");
}
}
class Drawing extends Art{
Drawing(){
System.out.print("Drawing ~~~``");
}
}
public class Cartoon extends Drawing{
public Cartoon(){
System.out.print("Cartoon ~~~``");
}
public static void main(String[] args) {
Cartoon c=new Cartoon();
}
}
==============================================================
【程序31】ColorUtil.java
/*
得到RGB值的分量
c:\>javac ColorUtil.java
c:\>java ColorUtil
WinColor=16711680,R=0,G=0,B=255
WinColor=255,R=255,G=0,B=0
WinColor=16761798,R=198,G=195,B=255
*/
public class ColorUtil
{
static int nWinBlueColor=16711680;
static int nWinRedColor=255;
static int nWinBlue255G195R198Color=16761798;
//AND,按位与
public static int Red(int color)
{
return color & 0xff;
}
public static int Green(int color)
{
return (color & 0xff00)/0xff;
}
public static int Blue(int color)
{
//return (color & 0xff0000)/0xff00;
return (color / 0x10000)& 0xff;
}
public static String WinRGBInfo(int color)
{
String C,R, G, B;
StringBuffer sb = new StringBuffer();
C="WinColor="+Integer.toString(color);
R=",R="+Integer.toString(Red(color));
G=",G="+Integer.toString(Green(color));
B=",B="+Integer.toString(Blue(color));
sb.append(C);
sb.append(R);
sb.append(G);
sb.append(B);
return sb.toString();
}
public static void main(String[] args){
String s1 = ColorUtil.WinRGBInfo(ColorUtil.nWinBlueColor);
System.out.println(s1);
String s2 = ColorUtil.WinRGBInfo(ColorUtil.nWinRedColor);
System.out.println(s2);
String s3 = ColorUtil.WinRGBInfo(ColorUtil.nWinBlue255G195R198Color);
System.out.println(s3);
}
}
==============================================================
【程序32】GetBitTest.java
/*
c:\>javac GetBitTest.java
c:\>java GetBitTest
0: 0 0 0 0 0 0 0 0
1: 0 0 0 0 0 0 0 1
2: 0 0 0 0 0 0 1 0
127: 0 1 1 1 1 1 1 1
128: 1 0 0 0 0 0 0 0
255: 1 1 1 1 1 1 1 1
*/
public class GetBitTest
{
public static int GetBit(char ch,int n)
{
return ((ch>>n)& 1);
}
public static void main(String[] args){
//char ch[]={-257,-256,-255,-128,-127,-2,-1,0,1,2,127,128,255,256,257};
//char ch[]={-128,-127,-2,-1,0,1,2,127};
char ch[]={0,1,2,127,128,255};
for(int i=0;i<6;i++)
{
System.out.print((int)ch[i]+":");
for(int j=7;j>=0;j--)
{
int ret=GetBit(ch[i],j);
System.out.print(" "+ret);
}
System.out.print("\n");
}
}
}
==============================================================
【程序33】prime.java
/*
c:\>javac prime.java
c:\>java prime
ret[0]=0
ret[1]=0
ret[2]=0
ret[3]=1
ret[4]=0
ret[5]=1
ret[6]=0
ret[7]=1
ret[8]=0
ret[9]=0
*/
public class prime
{
public static int isprime(int m)
{
int i;
int primes[]={2,3,5,7,11,17,19,23,29,-1};
if(m==1||m%2==0)return 0;
for (i=0;primes[i]>0;i++)
if (m==primes[i]) return 1;
for (i=3;i*i<=m;)
{
if (m%i==0) return 0;
i+=2;
}
return 1;
}
public static void main(String[] args){
int ret[]={0,0,0,0,0,0,0,0,0,0};
for(int i=0;i<10;i++)
{
ret[i]=isprime(i);
System.out.println("ret["+i+"]="+ret[i]);
}
}
}
==============================================================
【程序34】Sort.java
/*
直接插入排序
*/
public class Sort
{
public static void InsertSort(int a[],int n)
{
int i,j;
for(i=2;i<=n;i++)
if(a[i]<a[i-1])
{
a[0]=a[i];
a[i]=a[i-1];
for(j=i-2;a[0]<a[j];j--)
a[j+1]=a[j];
a[j+1]=a[0];
}
}
public static void Print(int a[],int n)
{
for(int i=0;i<n;i++)
System.out.println("a["+i+"]="+a[i]);
}
public static void main(String[] args){
int a[]={3,2,6,9,7,1,4,8,5,0};
Print(a,10);
InsertSort(a,10);
Print(a,10);
}
}
==============================================================
【程序35】BitRev.java
/*
c:\>javac BitRev.java
c:\>java BitRev
BitReverse(2,8)=64
BitReverse(64,8)=2
BitReverse(123456,8)=2
BitReverse(2,32)=1073741824
BitReverse(1073741824,32)=2
BitReverse(123456,32)=38240256
BitReverse(38240256,32)=123456
*/
public class BitRev
{
//二进制倒序操作
static int BitReverse(int src, int size)
{
int tmp = src;//待倒读的数
int des = 0;
for (int i=size-1; i>=0; i--)//二进制位数
{
des = ((tmp & 0x1) << i) | des;
tmp = tmp >> 1;
}
return des;
}
public static void main(String[] args) {
System.out.printf("BitReverse(%d,%d)=%d\n",2,8,BitReverse(2,8));
System.out.printf("BitReverse(%d,%d)=%d\n",64,8,BitReverse(64,8));
System.out.printf("BitReverse(%d,%d)=%d\n",123456,8,BitReverse(123456,8));
System.out.printf("BitReverse(%d,%d)=%d\n",2,32,BitReverse(2,32));
System.out.printf("BitReverse(%d,%d)=%d\n",1073741824,32,BitReverse(1073741824,32));
System.out.printf("BitReverse(%d,%d)=%d\n",123456,32,BitReverse(123456,32));
System.out.printf("BitReverse(%d,%d)=%d\n",38240256,32,BitReverse(38240256,32));
}
}
==============================================================
【程序36】Caesar.java
/*
c:\>javac Caesar.java
c:\>java Caesar
JavaECode("Text1",3)=Whaw1
JavaECode(JavaECode("Text1",3),-3)=Text1
fkmod26(12,3)=15
fkmod26(fkmod26(12,3),-3)=12
fkmod26(24,3)=1
fkmod26(fkmod26(24,3),-3)=24
*/
public class Caesar
{
//f(x)=(x+k)mod26,f^(-1)(x)=(x-k)mod26
static int fkmod26(int x,int k)
{
int ret=(x+k)%26;
if(ret<0)ret=ret+26;
if(ret>25)ret=ret-26;
return ret;
}
//凯撒加密
static void ECode(char[] str,int k)
{
int nsize=str.length;
for(int i=0;i<nsize;i++)
{
if(str[i]<='z'&&str[i]>='a')
str[i]=(char)(fkmod26((int)str[i]-97,k)+97);
if(str[i]<='Z'&&str[i]>='A')
str[i]=(char)(fkmod26((int)str[i]-65,k)+65);
}
}
static String JavaECode(String s1,int k)
{
char[] str=s1.toCharArray();
/*
int nsize=str.length;
for(int i=0;i<nsize;i++)
{
if(str[i]<='z'&&str[i]>='a')
str[i]=fkmod26(str[i]-97,k)+97;
if(str[i]<='Z'&&str[i]>='A')
str[i]=fkmod26(str[i]-65,k)+65;
}
*/
int nsize=str.length;
for(int i=0;i<nsize;i++)
{
if(str[i]<='z'&&str[i]>='a')
str[i]=(char)(fkmod26((int)str[i]-97,k)+97);
if(str[i]<='Z'&&str[i]>='A')
str[i]=(char)(fkmod26((int)str[i]-65,k)+65);
}
return new String(str);
}
public static void main(String[] args) {
System.out.printf("JavaECode(\"Text1\",3)=%s\n",JavaECode("Text1",3));
System.out.printf("JavaECode(JavaECode(\"Text1\",3),-3)=%s\n",JavaECode(JavaECode("Text1",3),-3));
System.out.printf("fkmod26(12,3)=%d\n",fkmod26(12,3));
System.out.printf("fkmod26(fkmod26(12,3),-3)=%d\n",fkmod26(fkmod26(12, 3), -3));
System.out.printf("fkmod26(24,3)=%d\n",fkmod26(24,3));
System.out.printf("fkmod26(fkmod26(24,3),-3)=%d\n",fkmod26(fkmod26(24, 3), -3));
}
}
==============================================================
【程序37】ComplexArg.java
/*
c:\>javac ComplexArg.java
c:\>java ComplexArg
GetAbilityType(0x00ff00ff)=15
GetAbilityIndex(0x00ff00ff)=15
GetAbilityValue(0x00ff00ff,1)=31
java中inline函数
原来一直不知道C++中的内联函数在Java中怎么实现。今天在翻《Java编程思想》的时候发现,final除了防止方法被override之外,还可以实现内联的效果。当然只是建议内联,只有方法比较小的时候才可以,编译器会智能考虑决定(其实C++也不是每个函数都能内联,只是控制权稍大些)。
另外,java中的private方法自动就是final,因为private方法不能被继承。
*/
public class ComplexArg
{
static final int GetAbilityType(int ability)
{
return ability & 0x0000000f;
}
static final int GetAbilityIndex(int ability)
{
return (ability & 0x00000ff0)>>4;
}
static final int GetAbilityValue(int type,int index)
{
return (type & 0x0000000f)|((index<<4) & 0x00000ff0);
}
public static void main(String[] args) {
System.out.printf("GetAbilityType(0x00ff00ff)=%d\n",GetAbilityType(0x00ff00ff));
System.out.printf("GetAbilityIndex(0x00ff00ff)=%d\n",GetAbilityIndex(0x00ff00ff));
System.out.printf("GetAbilityValue(0x00ff00ff,1)=%d\n",GetAbilityValue(0x00ff00ff,1));
}
}
==============================================================
【程序38】EulerPhi.java
/*
c:\>javac EulerPhi.java
c:\>java EulerPhi
totient(1)=1
totient(2)=1
totient(3)=2
totient(4)=2
totient(5)=4
totient(6)=2
totient(7)=6
totient(8)=4
totient(9)=6
totient(10)=4
totient(11)=10
totient(12)=4
totient(13)=12
totient(14)=6
totient(15)=8
totient(16)=8
totient(17)=16
totient(18)=6
totient(19)=18
totient(20)=8
totient(21)=12
totient(22)=10
totient(23)=22
totient(24)=8
totient(25)=20
totient(26)=12
totient(27)=18
totient(28)=12
totient(29)=28
totient(30)=8
totient(31)=30
totient(32)=16
totient(33)=20
totient(34)=16
totient(35)=24
totient(36)=12
totient(37)=36
totient(38)=18
totient(39)=24
totient(40)=16
totient(41)=40
totient(42)=12
totient(43)=42
totient(44)=20
totient(45)=24
totient(46)=22
totient(47)=46
totient(48)=16
totient(49)=42
totient(50)=20
totient(51)=32
totient(52)=24
totient(53)=52
totient(54)=18
totient(55)=40
totient(56)=24
totient(57)=36
totient(58)=28
totient(59)=58
totient(60)=16
totient(61)=60
totient(62)=30
totient(63)=36
totient(64)=32
totient(65)=48
totient(66)=20
totient(67)=66
totient(68)=32
totient(69)=44
totient(70)=24
totient(71)=70
totient(72)=24
totient(73)=72
totient(74)=36
totient(75)=40
totient(76)=36
totient(77)=60
totient(78)=24
totient(79)=78
totient(80)=32
totient(81)=54
totient(82)=40
totient(83)=82
totient(84)=24
totient(85)=64
totient(86)=42
totient(87)=56
totient(88)=40
totient(89)=88
totient(90)=24
totient(91)=72
totient(92)=44
totient(93)=60
totient(94)=46
totient(95)=72
totient(96)=32
totient(97)=96
totient(98)=42
totient(99)=60
totient(100)=40
*/
public class EulerPhi
{
//求2个数的最大公约数
static int GCD(int a, int b)
{
if(a*b<0)
return -GCD(Math.abs(a),Math.abs(b));
int temp=0;
if(a<b)
{
temp=a;
a=b;
b=temp;
}
if(a%b==0)
return b;
else
return GCD(a%b,b);
//return 0;
}
static int Iscoprime(int a, int b)
{
int ret=0;
if(GCD(a,b)==1)
ret=1;
return ret;
}
//欧拉φ函数
static int totient(int num)
{
int count=0;
if(num==1)
return 1;
for(int i=1;i<=num-1;i++)
{
count+=Iscoprime(num,i);
}
return count;
}
public static void main(String[] args) {
int ret=GCD(12,32);
int ret1=GCD(-12,32);
int ret2=GCD(12,-32);
for(int i=1;i<=100;i++)
System.out.printf("totient(%d)=%d\n",i,totient(i));
}
}
==============================================================
【程序39】switch_case_default.java
/*
c:\>javac switch_case_default.java
c:\>java switch_case_default
没有记录这一年的大事
c:\>javac switch_case_default.java
c:\>java switch_case_default
武王二年(-1045)武王安抚殷民,分封诸侯。
*/
public class switch_case_default
{
public static void main(String[] args) {
//int n=-104;
int n=-1045;
switch (n)
{
case -1046:
{
String s1="(-1046)牧野之战。";
System.out.printf("%s\n",s1);
break;
}
case -1045:
{
String s1= "武王二年(-1045)武王安抚殷民,分封诸侯。";
System.out.printf("%s\n",s1);
break;
}
default:
{
String s1= "没有记录这一年的大事";
//char[] cArr1=s1.toCharArray();
System.out.printf("%s\n",s1);
break;
}
}
}
}
==============================================================
【程序40】TestAC.java
/*
c:\>javac TestAC.java
c:\>java TestAC
apailie(5,3)=60
apailie(5,2)=20
czuhe(5,3)=10
czuhe(5,2)=10
*/
public class TestAC {
//n中取m的排列数P(m上,n下)
/*求a(n,m)*/
public static int apailie(int n,int m)
{
if(m==0)
return 1;
else
return (n-m+1)*apailie(n,m-1);
}
//n中取m的组合数C(m上,n下)
/*c(n,m)=a(n,m)/a(m,m)*/
public static int czuhe(int n,int m)
{
return apailie(n,m)/apailie(m,m);
}
int calca(int n,int m)
{
return apailie(n,m);
}
int calcc(int n,int m)
{
return czuhe(n,m);
}
public static void main(String[] args) {
System.out.printf("apailie(5,3)=%d\n",apailie(5,3));
System.out.printf("apailie(5,2)=%d\n",apailie(5,2));
System.out.printf("czuhe(5,3)=%d\n",czuhe(5,3));
System.out.printf("czuhe(5,2)=%d\n",czuhe(5,2));
}
}
==============================================================
【程序41】TestCPU.java
/*
c:\>javac TestCPU.java
c:\>java TestCPU
LITTLE_ENDIAN
Intel系列CPU采用Little Endian
#include <iostream>
using namespace std;
int main()
{
unsigned int i = 0x11112222;
unsigned char * p = (unsigned char *)&i;
if(*p == 0x22)
{
//Intel系列CPU采用Little Endian存储格式来存放基本类型变量
printf("小端This is little endian system\n");
}
else
{
printf("大端This is big endian system\n");
}
system("pause");
return 0;
}
*/
import java.nio.ByteOrder;
public class TestCPU {
public static void main(String[] args) {
if(ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN)
{
System.out.println("BIG_ENDIAN");
}
else
{
System.out.println("LITTLE_ENDIAN");
}
}
}
==============================================================
【程序42】XOR.java
/*
简单异或密码(simple XOR cipher)是密码学中中一种简单的加密算法。
异或运算:m^n^n = m;
利用异或运算的特点,可以对数据进行简单的加密和解密。
m=91
n=104
m^n=51
详细出处参考:http://www.jb51.net/article/44682.htm
c:\>javac XOR.java
c:\>java XOR
加密后:寬晼嚫桑聳讥讥飨
2次加密后:宜昌四校考试试题
*/
public class XOR
{
static int j=0;
/**
* 简单异或加密解密算法
* @param str 要加密的字符串
* @return
*/
private static String encode2(String str) {
int code = 112; // 密钥
char[] charArray = str.toCharArray();
for(int i = 0; i < charArray.length; i++){
charArray[i] = (char) (charArray[i] ^ code);
}
return new String(charArray);
}
static char dochar(char ch,char[] pwd)
{
int j=0;
int j0=0;
char ret=(char)(ch^pwd[j>=j0?j=0:j++]);
return ret;
}
//用异或算法(字节与密码异或方式)实现字节的简单加密,当解密时,只需再运行一遍加密程序即可
static char XOREn(char ch,char[] pwd)
{
//int j=0;
int j0=0;
char ch2,ch0;
//while(++j0<pwd.length);
j0=pwd.length;
ch0=pwd[j>=j0?j=0:j++];//有效密码字节ch0
ch2=(char)(ch^ch0);//输入字节ch,输出字节ch2
return ch2;
}
public static void main(String[] args) {
System.out.printf("异或的法则是相同的为0,不同的为1:%d,%c\n",91^104,91^104);
System.out.printf("异或加密原理:%d,%c\n",51^104,51^104);
String s1="han";
char[] cArr=s1.toCharArray();
//char r1=dochar((char)91,cArr);
char r1=XOREn((char)91,cArr);
System.out.println("r1:"+r1+"("+(char)r1+")");
String ret1=encode2("宜昌四校考试试题");
System.out.println("加密后:"+ret1);
String ret2=encode2(ret1);
System.out.println("2次加密后:"+ret2);
}
}
==============================================================
【程序43】FanXing.java
/*
Java泛型加法的实现
c:\>javac FanXing.java
c:\>java FanXing
8.0
*/
//定义一个泛型Sum
class Sum<T1,T2>{
public T1 x;
public T2 y;
public void setX(T1 newX){
x=newX;
}
public void setY(T2 newY){
y=newY;
}
}
//测试泛型类
public class FanXing{
public static void main(String[] args){
Sum<Double,Integer> s=new Sum<Double,Integer>();
s.setX(2.0);
s.setY(6);
System.out.println(s.x+s.y);
}
}
==============================================================
【程序44】GenericAdd.java
/*
c:\>javac GenericAdd.java
c:\>java GenericAdd
整数和:7.0
浮点数和:10.0
双精度浮点数和:100.0
长整数和:1000.0
*/
public class GenericAdd {
// 泛型方法实现两个数相加
public <T extends Number> double add(T t1, T t2) {
double sum = 0.0;
sum = t1.doubleValue() + t2.doubleValue();
return sum;
}
public static void main(String[] args) {
test();
}
public static void test() {
GenericAdd addTest = new GenericAdd();// 新建GenericAdd类
int num1 = 3;
int num2 = 4;
System.out.println("整数和:" + addTest.add(num1, num2));// 整数相加
float num3 = 3.0f;
float num4 = 7.0f;
System.out.println("浮点数和:" + addTest.add(num3, num4));// 浮点数相加
double num5 = 99.0;
double num6 = 1.0;
System.out.println("双精度浮点数和:" + addTest.add(num5, num6));// 双精度浮点数相加
long num7 = 300;
long num8 = 700;
System.out.println("长整数和:" + addTest.add(num7, num8));// 长整数相加
}
}
==============================================================
【程序45】HelloWorld.java
/*
javac HelloWorld.java
java HelloWorld
*/
public class HelloWorld {
static final int EWX_LOGOFF = 0;//所有的进程被强制终止,并且用户退出登录
static final int EWX_SHUTDOWN = 1;
static final int EWX_REBOOT = 2;//计算机系统被关机并重新启动
static final int EWX_FORCE = 4;//所有的进程都被强制终止
static final int EWX_POWEROFF = 8;
static final int EWX_RESET = EWX_LOGOFF + EWX_FORCE + EWX_REBOOT;//三个标识的组合
public static void main(String args[]) {
int uFlags=EWX_RESET;
System.out.println("uFlags="+uFlags);
}
}
==============================================================
【程序46】Test2.java
/*
c:\>javac Test2.java
c:\>java Test2
0123456789
*/
import java.util.Arrays;
public class Test2{
public static int[] bubbleSort(int[] args){//冒泡排序算法
for(int i=0;i<args.length-1;i++){
for(int j=i+1;j<args.length;j++){
if (args[i]>args[j]){
int temp=args[i];
args[i]=args[j];
args[j]=temp;
}
}
}
return args;
}
//冒泡升序排序
public static void pibub(int p[],int n)
{
int m,k,j,i,d;
k=0; m=n-1;
while (k<m)
{
j=m-1; m=0;
for (i=k; i<=j; i++)
if (p[i]>p[i+1])
{
d=p[i];
p[i]=p[i+1];
p[i+1]=d;
m=i;
}
j=k+1;
k=0;
for (i=m; i>=j; i--)
if (p[i-1]>p[i])
{
d=p[i];
p[i]=p[i-1];
p[i-1]=d;
k=i;
}
}
return;
}
//有问题
public static void pibub(int p[],int n,int ascending)//ascending=1表示升序,0表示降序
{
int temp,i,j;
if(ascending==1)
{
for(i=0;i<n;i++)
{
for(j=0;j<i;j++)
{
if(p[j]>p[i])//选择升序排序
{
temp=p[i];
//插入
for(int k=i;k>=j;k--)p[k]=p[k-1];
p[j]=temp;
}
}
}
}
else
{
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1;j++)
if(p[j]<p[j+1])//选择降序
{
temp=p[j];
p[j]=p[j+1];
p[j+1]=temp;
}
}
}
}
//冒泡升序排序
public static void BubbleSort(int a[],int n)
{
int i,j,t;
for(j=0;j<n-2;j++)
//for(i=0;i<n-2-j;i++)
for(i=0;i<n-1-j;i++)
if(a[i]>a[i+1])
{
t=a[i];
a[i]=a[i+1];
a[i+1]=t;
}
/*
int i,j;
int change;
int temp;
for(i=n-1,change=1;i>=1&&change;i--)
{
change=0;
for(j=1;j<=i;j++)
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
change=1;
}
}
*/
}
//实现对数组的降序排序
public static void DescSort(int arr[], int n)
{
int temp;
for(int i = 1; i < n; i++)
{
for(int k = 0; k < n - i; k++)//曾经在这儿出界
{
if(arr[k] < arr[k + 1])
{
temp = arr[k];
arr[k] = arr[k + 1];
arr[k + 1] = temp;
}
}
}
}
public static int[] selectSort(int[] args){//选择排序算法
for (int i=0;i<args.length-1 ;i++ ){
int min=i;
for (int j=i+1;j<args.length ;j++ ){
if (args[min]>args[j]){
min=j;
}
}
if (min!=i){
int temp=args[i];
args[i]=args[min];
args[min]=temp;
}
}
return args;
}
public static int[] insertSort(int[] args){//插入排序算法
for(int i=1;i<args.length;i++){
for(int j=i;j>0;j--){
if (args[j]<args[j-1]){
int temp=args[j-1];
args[j-1]=args[j];
args[j]=temp;
}else break;
}
}
return args;
}
//错误
public static void InsertSort(int a[],int n)
{
int i,j;
for(i=1;i<n;i++)
if(a[i]<a[i-1])
{
a[0]=a[i];
a[i]=a[i-1];
for(j=i-2;a[0]<a[j];j--)
a[j+1]=a[j];
a[j+1]=a[0];
}
}
//快速升序排序
public static void QSort(int arr[],int startPos,int endPos)
{
int i,j;
int ch;
ch=arr[startPos];
i=startPos;
j=endPos;
while(i<j)
{
while(arr[j]>=ch && i<j)--j;
arr[i]=arr[j];
while(arr[i]<=ch && i<j)++i;
arr[j]=arr[i];
}
arr[i]=ch;
if(i-1>startPos)
QSort(arr,startPos,i-1);
if(endPos>i+1)
QSort(arr,i+1,endPos);
}
public static void main(String[] args){
//int[] a={5,4,2,4,9,1};
int[] a={5,6,7,8,9,0,1,2,3,4};
//Arrays.sort(a);//进行快速升序排序
//bubbleSort(a);//冒泡升序排序
//selectSort(a);//选择升序排序
//insertSort(a);//插入升序排序
//InsertSort(a,a.length);
//BubbleSort(a,a.length);
DescSort(a,a.length);
//pibub(a,a.length,1);//整数冒泡升序排序
//pibub(a,a.length);
//QSort(a,0,a.length-1);
for(int i: a){
System.out.print(i);
}
}
}
==============================================================
【程序47】Test3.java
//package com.xy.example;
import java.util.Arrays;
public class Test3{
public static void main(String[] args) {
String[] text = { "a", "ab", "ac", "abc", "de", "bc", "e" };
String temp = "";
for (int i = 0; i < text.length; i++) {
//String temp = text[i];
for (int j = i; j < text.length - i; j++) {
if (temp.compareTo(text[j]) > 0) {
text[i] = text[j];
text[j] = temp;
}
}
}
System.out.println(Arrays.toString(text));
// 如果要排序的为字符串
String sortStr = "astbxefhigpqaifjcbazyx";
char[] arrayCh = sortStr.toCharArray(); //1,把sortStr转换为字符数组
Arrays.sort(arrayCh);//2,利用数组帮助类自动排序
System.out.println(Arrays.toString(arrayCh));//3,输出
// 如果要排序的为字符串数组
// 英文字母序排列
//String[] sortStrArr= new String[]{"main","gou","zhao","lin","wang","zhang","li","zhen","ma","sub","china","beijin","liang","juan","yan","teacher","student","qssort"};
String[] sortStrArr= new String[]{"main","gou","zhao","lin","wang","zhang","li","zhen","ma","sub"};
Arrays.sort(sortStrArr);//2,利用数组帮助类自动排序
System.out.println(Arrays.toString(sortStrArr));//3,输出
}
}
==============================================================
【程序48】Transfer.java
/*
转换字符串,大写变小写,小写变大写,数字不变,其他变为*
*/
public class Transfer{
static char tolower(char ch)
{
if(ch >= 'A' && ch<='Z')
{
return (char)(ch+('a'-'A'));
}
else
{
return ch;
}
}
static char toupper(char ch)
{
if(ch >= 'a' && ch<='z')
{
return (char)(ch-('a'-'A'));
}
else
{
return ch;
}
}
public static void main(String[] args){
String a="HELLO JAVA ME";
//char e=97;//相当于char e='a';因为小写a的unicode码是97(unicode包含了Ascii )所以最后一个大写A出现在第9的索引
char e='a';
//int b=a.toUpperCase().lastIndexOf(String.valueOf(e).toUpperCase());
//int b=a.toUpperCase().lastIndexOf(tolower(e));//-1
int b=a.toUpperCase().lastIndexOf(toupper(e));//9
System.out.println(b);
String str = "ABC123abcfadfjbJBHJHJDsa";
StringBuffer sb = new StringBuffer();
int i;
//char ch;
for(i = 0; i <= str.length()-1;i ++)
{
char ch;
//通过str.charAt(i)遍历出字符串中每个字符
if(str.charAt(i) >= 'a' && str.charAt(i) <= 'z'){//判断字符是否在a-z之间(小写)
ch = (char) (str.charAt(i)-32);//如果为小写则转换为相应大写,赋值给ch
}
else if(str.charAt(i) >= 'A' && str.charAt(i) <= 'Z'){//判断字符是否在A-Z之间(大写)
ch = (char) (str.charAt(i)+32);//如果为大写则转换为相应小写,赋值给ch
}
else if(str.charAt(i)>='0'&&str.charAt(i)<='9'){//判断字符是否在0-9之间(数字)
ch = str.charAt(i);//如果为数字,将原数字赋值给ch
}
else
{
ch = '*';//如果为其他则转为*号
}
sb.append(ch);//将字符追加到sb序列
}
String trStr = sb.toString();//将StringBuffer转换为String类型
System.out.println(sb.toString());
}
}
==============================================================
【程序49】BinoTest.java
/*
C:\>javac BinoTest.java
C:\>java BinoTest
bin=0.31250000000000033
*/
public class BinoTest
{
/*
计算符合二项式分布事件的概率
n:试验次数
p:一次试验中事件A出现的概率
x:n次试验中事件A出现的次数
返回值:事件A出现x次的概率
*/
public static double Bino(int n,double p,int x)
{
double NN=0,NI=0,M=0,C=0;
double Q;
Q=1-p;
if(x==0)
{
return Math.pow(Q,n);
}
for(int i=1;i<=n;i++)
NN=NN+Math.log((double)i);
for(int i=1;i<=x;i++)
M=M+Math.log((double)i);
for(int i=1;i<=n-x;i++)
NI=NI+Math.log((double)i);
C=NN-M-NI;
C=C+Math.log(Math.pow(p,x))+Math.log(Math.pow(Q,n-x));
return Math.exp(C);
}
public static void main(String[] args){
double bin=Bino(6,0.5,3);
System.out.println("bin="+bin);
}
}
==============================================================
【程序50】MyFft.java
/*
java版快速傅立叶变换(基-2FFT)
author by soulnew@gmail.com
C:\>javac MyFft.java
C:\>java MyFft
now is the loop and l=1
8.0+j0.0
-8.0+j0.0
16.0+j0.0
-8.0+j0.0
12.0+j0.0
-8.0+j0.0
20.0+j0.0
-8.0+j0.0
10.0+j0.0
-8.0+j0.0
18.0+j0.0
-8.0+j0.0
14.0+j0.0
-8.0+j0.0
22.0+j0.0
-8.0+j0.0
now is the loop and l=2
24.0+j0.0
-8.0+j8.0
-8.0+j0.0
-7.999999999999999+j-8.0
32.0+j0.0
-8.0+j8.0
-8.0+j0.0
-7.999999999999999+j-8.0
28.0+j0.0
-8.0+j8.0
-8.0+j0.0
-7.999999999999999+j-8.0
36.0+j0.0
-8.0+j8.0
-8.0+j0.0
-7.999999999999999+j-8.0
now is the loop and l=4
56.0+j0.0
-8.0+j19.31370849898476
-8.0+j8.0
-8.0+j3.3137084989847594
-8.0+j0.0
-7.999999999999999+j-3.3137084989847594
-7.999999999999999+j-8.0
-7.999999999999997+j-19.31370849898476
64.0+j0.0
-8.0+j19.31370849898476
-8.0+j8.0
-8.0+j3.3137084989847594
-8.0+j0.0
-7.999999999999999+j-3.3137084989847594
-7.999999999999999+j-8.0
-7.999999999999997+j-19.31370849898476
now is the loop and l=8
120.0+j0.0
-8.0+j40.21871593700678
-8.0+j19.31370849898476
-8.000000000000002+j11.972846101323912
-8.0+j8.0
-7.999999999999999+j5.345429103354391
-8.0+j3.3137084989847594
-8.000000000000002+j1.5912989390372623
-8.0+j0.0
-8.0+j-1.5912989390372623
-7.999999999999999+j-3.3137084989847594
-7.999999999999998+j-5.345429103354393
-7.999999999999999+j-8.0
-7.999999999999999+j-11.97284610132391
-7.999999999999997+j-19.31370849898476
-7.999999999999993+j-40.21871593700678
120.0+j0.0
-8.0+j40.21871593700678
-8.0+j19.31370849898476
-8.000000000000002+j11.972846101323912
-8.0+j8.0
-7.999999999999999+j5.345429103354391
-8.0+j3.3137084989847594
-8.000000000000002+j1.5912989390372623
-8.0+j0.0
-8.0+j-1.5912989390372623
-7.999999999999999+j-3.3137084989847594
-7.999999999999998+j-5.345429103354393
-7.999999999999999+j-8.0
-7.999999999999999+j-11.97284610132391
-7.999999999999997+j-19.31370849898476
-7.999999999999993+j-40.21871593700678
*/
//package com.soulnew.Math;
public class MyFft{
public MyFft(){
}
/*
*实现倒码
**/
public static complex[] changedLow(complex[] a,int length){
int mr=0;
for(int m=1;m<length;++m){
int l=length/2;
while(mr+l>=length){
l=l>>1; //右移相当于,l除以2
}
mr=mr%l+l;
if(mr>m){
complex t=new complex();
t=a[m];
a[m]=a[mr];
a[mr]=t;
}
}
return a;
}
/*
*乘积因子
**/
public complex complex_exp(complex z){
complex r=new complex();
double expx=Math.exp(z.r);
r.r=expx*Math.cos(z.i);
r.i=expx*Math.sin(z.i);
return r;
}
/*
*基-2 fft蝶形变换
*fft_tepy=1正变换, -1反变换
**/
public complex[] fft_2(complex[] a,int length,int fft_tepy){
double pisign=fft_tepy*Math.PI;
// System.out.print(" pisign:"+pisign+"\n");
complex t=new complex();
int l=1;
while(l<length){
for(int m=0;m<l;++m){
int temp_int=l*2; //左移相当于,l乘以2
for(int i=m;temp_int<0?i>=(length-1):i<length;i+=temp_int){
complex temp=new complex(0.0,m*pisign/l);
complex temp_exp=complex_exp(temp);
t.r=a[i+l].r*temp_exp.r-a[i+l].i*temp_exp.i;
t.i=a[i+l].r*temp_exp.i+a[i+l].i*temp_exp.r;
a[i+l].r=a[i].r-t.r;
a[i+l].i=a[i].i-t.i;
a[i].r=a[i].r+t.r;
a[i].i=a[i].i+t.i;
} // end for i
} // end for m
System.out.print("\n now is the loop and l="+l+"\n");
for(int c=0;c<length;c++){
System.out.print(a[c].r+"+j"+a[c].i+"\n");
}
l=l*2;
}//end while
//左移相当于,l乘以2
return a;
}
complex b[];
/*
*
*main
*
*
**/
public static void main(String arg[]){
MyFft mf=new MyFft();
final int n=16;
int dd[]=new int[n];
mf.b= new complex[n];
for(int c=0;c<n;c++){ //轮流赋值
mf.b[c]=new complex(c,0);
// System.out.print(mf.b[c].r+"+j"+mf.b[c].i+"\n");
}
System.out.print("\n\n");
mf.b=mf.changedLow(mf.b,n);
mf.b=mf.fft_2(mf.b,n,-1);
//输出
for(int c=0;c<n;c++){
System.out.print(mf.b[c].r+"+j"+mf.b[c].i+"\n");
}
}
}
/*
*复数类
**/
class complex{
double r,i;
public complex(){
}
public complex(double r,double i){
this.r=r; //实部
this.i=i; //虚部
}
}
==============================================================
【程序51】FFT.java
/*************************************************************************
* Compilation: javac FFT.java
* Execution: java FFT N
* Dependencies: Complex.java
*
* Compute the FFT and inverse FFT of a length N complex sequence.
* Bare bones implementation that runs in O(N log N) time. Our goal
* is to optimize the clarity of the code, rather than performance.
*
* Limitations
* -----------
* - assumes N is a power of 2
*
* - not the most memory efficient algorithm (because it uses
* an object type for representing complex numbers and because
* it re-allocates memory for the subarray, instead of doing
* in-place or reusing a single temporary array)
*
*************************************************************************/
public class FFT {
// compute the FFT of x[], assuming its length is a power of 2
public static Complex[] fft(Complex[] x) {
int N = x.length;
// base case
if (N == 1) return new Complex[] { x[0] };
// radix 2 Cooley-Tukey FFT
if (N % 2 != 0) { throw new RuntimeException("N is not a power of 2"); }
// fft of even terms
Complex[] even = new Complex[N/2];
for (int k = 0; k < N/2; k++) {
even[k] = x[2*k];
}
Complex[] q = fft(even);
// fft of odd terms
Complex[] odd = even; // reuse the array
for (int k = 0; k < N/2; k++) {
odd[k] = x[2*k + 1];
}
Complex[] r = fft(odd);
// combine
Complex[] y = new Complex[N];
for (int k = 0; k < N/2; k++) {
double kth = -2 * k * Math.PI / N;
Complex wk = new Complex(Math.cos(kth), Math.sin(kth));
y[k] = q[k].plus(wk.times(r[k]));
y[k + N/2] = q[k].minus(wk.times(r[k]));
}
return y;
}
// compute the inverse FFT of x[], assuming its length is a power of 2
public static Complex[] ifft(Complex[] x) {
int N = x.length;
Complex[] y = new Complex[N];
// take conjugate
for (int i = 0; i < N; i++) {
y[i] = x[i].conjugate();
}
// compute forward FFT
y = fft(y);
// take conjugate again
for (int i = 0; i < N; i++) {
y[i] = y[i].conjugate();
}
// divide by N
for (int i = 0; i < N; i++) {
y[i] = y[i].times(1.0 / N);
}
return y;
}
// compute the circular convolution of x and y
public static Complex[] cconvolve(Complex[] x, Complex[] y) {
// should probably pad x and y with 0s so that they have same length
// and are powers of 2
if (x.length != y.length) { throw new RuntimeException("Dimensions don't agree"); }
int N = x.length;
// compute FFT of each sequence
Complex[] a = fft(x);
Complex[] b = fft(y);
// point-wise multiply
Complex[] c = new Complex[N];
for (int i = 0; i < N; i++) {
c[i] = a[i].times(b[i]);
}
// compute inverse FFT
return ifft(c);
}
// compute the linear convolution of x and y
public static Complex[] convolve(Complex[] x, Complex[] y) {
Complex ZERO = new Complex(0, 0);
Complex[] a = new Complex[2*x.length];
for (int i = 0; i < x.length; i++) a[i] = x[i];
for (int i = x.length; i < 2*x.length; i++) a[i] = ZERO;
Complex[] b = new Complex[2*y.length];
for (int i = 0; i < y.length; i++) b[i] = y[i];
for (int i = y.length; i < 2*y.length; i++) b[i] = ZERO;
return cconvolve(a, b);
}
// display an array of Complex numbers to standard output
public static void show(Complex[] x, String title) {
System.out.println(title);
System.out.println("-------------------");
for (int i = 0; i < x.length; i++) {
System.out.println(x[i]);
}
System.out.println();
}
/*********************************************************************
* Test client and sample execution
*
* % java FFT 4
* x
* -------------------
* -0.03480425839330703
* 0.07910192950176387
* 0.7233322451735928
* 0.1659819820667019
*
* y = fft(x)
* -------------------
* 0.9336118983487516
* -0.7581365035668999 + 0.08688005256493803i
* 0.44344407521182005
* -0.7581365035668999 - 0.08688005256493803i
*
* z = ifft(y)
* -------------------
* -0.03480425839330703
* 0.07910192950176387 + 2.6599344570851287E-18i
* 0.7233322451735928
* 0.1659819820667019 - 2.6599344570851287E-18i
*
* c = cconvolve(x, x)
* -------------------
* 0.5506798633981853
* 0.23461407150576394 - 4.033186818023279E-18i
* -0.016542951108772352
* 0.10288019294318276 + 4.033186818023279E-18i
*
* d = convolve(x, x)
* -------------------
* 0.001211336402308083 - 3.122502256758253E-17i
* -0.005506167987577068 - 5.058885073636224E-17i
* -0.044092969479563274 + 2.1934338938072244E-18i
* 0.10288019294318276 - 3.6147323062478115E-17i
* 0.5494685269958772 + 3.122502256758253E-17i
* 0.240120239493341 + 4.655566391833896E-17i
* 0.02755001837079092 - 2.1934338938072244E-18i
* 4.01805098805014E-17i
*
*********************************************************************/
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
Complex[] x = new Complex[N];
// original data
for (int i = 0; i < N; i++) {
x[i] = new Complex(i, 0);
x[i] = new Complex(-2*Math.random() + 1, 0);
}
show(x, "x");
// FFT of original data
Complex[] y = fft(x);
show(y, "y = fft(x)");
// take inverse FFT
Complex[] z = ifft(y);
show(z, "z = ifft(y)");
// circular convolution of x with itself
Complex[] c = cconvolve(x, x);
show(c, "c = cconvolve(x, x)");
// linear convolution of x with itself
Complex[] d = convolve(x, x);
show(d, "d = convolve(x, x)");
}
}
==============================================================
【程序52】FPoint2D.java
/*
c:\>javac FPoint2D.java
c:\>java FPoint2D
a.x = 3.098076
a.y = -0.6339746
a.x = 0.70710677
a.y = 0.70710677
*/
public class FPoint2D
{
public float x, y;
// 平面一点A(x1,y1)绕另一点O(x0,y0)顺时针旋转角度k后的坐标点B(x2,y2)
public static FPoint2D SO2(float x1,float y1,float x0,float y0,float k) {
k=new Float(Math.toRadians(k));
float x2=new Float((x1-x0)*Math.cos(k) +(y1-y0)*Math.sin(k)+x0);
float y2=new Float(-(x1-x0)*Math.sin(k) + (y1-y0)*Math.cos(k)+y0);
FPoint2D b = new FPoint2D();
b.x=x2;
b.y=y2;
return b;
}
public static void main(String[] args) {
{
FPoint2D a = SO2((float)3.0,(float)1.0,(float)0.0,(float)0.0,(float)30);
System.out.println("a.x = " + a.x);
System.out.println("a.y = " + a.y);
}
{
FPoint2D a = SO2((float)1.0,(float)0.0,(float)0.0,(float)0.0,(float)-45);
System.out.println("a.x = " + a.x);
System.out.println("a.y = " + a.y);
}
}
}
==============================================================
【程序53】
定积分FP.java
c:\>javac FP.java
c:\>java FP
t=1.462652e+00
root@iZ14rcmneyrcltZ:~/cpptest/javatest# javac FP.java
root@iZ14rcmneyrcltZ:~/cpptest/javatest# java FP
t=1.462652e+00
c/c++
typedef double(*FP)(double x);
double bcsimp(double(*bcsimpf)(double x),double a,double b,double eps)
t=1.462652e+000
public class FP
{
// 被积函数
public static float func(float x)
{
//return(x*Math.sin(x));
return (float)(Math.sqrt(x));
}
public static double Func(double x)
{
double y;
y=Math.exp(x*x);
return(y);
}
// 梯形法求定积分
public static float integral(FP fun,float a,float b,int n)
{
float s,h,y;
int i;
s=(fun.func(a)+fun.func(b))/2;
h=(b-a)/n;// 积分步长
for(i=1;i<n;i++)
s=s+fun.func(a+i*h);
y=s*h;
return y;
}
/*
变步长辛普生法
a为积分下限;b为积分上限;eps为精度要求
*/
public static double bcsimp(FP bcsimpf,double a,double b,double eps){
int n,k;
double h,t1,t2,s1,s2,ep,p,x;
s2=0;
n=1;
h=b-a;
t1=h*(bcsimpf.Func(a)+bcsimpf.Func(b))/2.0;
s1=t1;
ep=eps+1.0;
while(ep>=eps)
{
p=0.0;
for(k=0;k<=n-1;k++)
{
x=a+(k+0.5)*h;
p=p+bcsimpf.Func(x);
}
t2=(t1+h*p)/2.0;
s2=(4.0*t2-t1)/3.0;
ep=Math.abs(s2-s1);
t1=t2;
s1=s2;
n=n+n;
h=h/2.0;
}
return(s2);
}
public static void main(String[] args) {
{
FP bcsimpf = new FP();
double a,b,eps,t;
a=0.0;
b=1.0;
eps=0.000001;
t=bcsimp(bcsimpf,a,b,eps);
System.out.printf("t=%e\n",t);
float y;
y=integral(bcsimpf,(float)1.0,(float)2.0,150);
//y=integral(bcsimpf,0,1,150);
System.out.printf("y=%f\n",y);
}
}
}
==============================================================
【程序54】mathlib.java
/*
c:\>javac mathlib.java
c:\>java mathlib
Si(0.00)= 0.0000000
Si(1.00)= 0.9460831
Si(1000.00)= 1.5701391
请输入N:4
1
2
3
4
test and verify:
10.000000
-2.000000
-2.000000
-2.000000
0.000000
2.000000
-0.000000
-2.000000
1.000000
2.000000
3.000000
4.000000
-0.000000
0.000000
-0.000000
-0.000000
*/
import java.util.Scanner;
public class mathlib
{
static double lsinn(double x)
{
double t[]={-0.9061798459,-0.5384693101,0.0,0.5384693101,0.9061798459};
double c[]={0.2369268851,0.4786286705,0.5688888889,0.4786286705,0.2369268851};
int m,i,j;
double s,p,ep,h,aa,bb,w,xx,g;
m=1;
g=0;
if(x==0)
return(0.0);
h=Math.abs(x);
s=Math.abs(0.0001*h);
p=1.0e+35;
ep=0.000001;
g=0.0;
while((ep>=0.0000001)&&(Math.abs(h)>s))
{
g=0.0;
for (i=1;i<=m;i++)
{
aa=(i-1.0)*h; bb=i*h;
w=0.0;
for(j=0;j<=4;j++)
{
xx=((bb-aa)*t[j]+(bb+aa))/2.0;
w=w+Math.sin(xx)/xx*c[j];
}
g=g+w;
}
g=g*h/2.0;
ep=Math.abs(g-p)/(1.0+Math.abs(g));
p=g;
m=m+1;
h=Math.abs(x)/m;
}
return(g);
}
static void kkfft(double[] pr,double[] pi,int n,int k,double[] fr,double[] fi,int l,int il)
{
return;
}
//利用定义计算任意点实序列的一维DFT
static int DFT1(double pr[],double pi[],double fr[],double fi[],int N,int inv)
{
double sr,si;
if(inv==1)
{
for(int j=0;j<N;j++)
{
sr=0.0;
si=0.0;
for(int k=0;k<N;k++)
{
sr+=pr[k]*Math.cos(-6.2831853068*j*k/N);
si+=pr[k]*Math.sin(-6.2831853068*j*k/N);
}
fr[j]=sr;
fi[j]=si;
}
for(int i=0;i<N; i++)
{
System.out.printf("%f\n",fr[i]);
}
System.out.printf("\n");
for(int i=0; i<N; i++)
{
System.out.printf("%f\n",fi[i]);
}
System.out.printf("\n\n");
}
if(inv==-1)
{
for(int k=0;k<N;k++)
{
sr=0.0;
si=0.0;
for(int j=0;j<N;j++)
{
sr+= fr[j]*Math.cos(6.2831853068*j*k/N)-fi[j]*Math.sin(6.2831853068*j*k/N);
si+= fr[k]*Math.sin(6.2831853068*j*k/N)+fi[j]*Math.cos(6.2831853068*j*k/N);
}
pr[k]=sr/N;
pi[k]=si/N;
}
for(int i=0;i<N; i++)
{
System.out.printf("%f\n",pr[i]);
}
System.out.printf("\n");
for(int i=0; i<N; i++)
{
System.out.printf("%f\n",pi[i]);
}
System.out.printf("\n\n");
}
return 0;
}
public static void main(String[] args)
{
System.out.printf("Si(%4.2f)=%12.7f\n",0.0,lsinn(0.0));//正弦积分
System.out.printf("Si(%4.2f)=%12.7f\n",1.0,lsinn(1.0));//正弦积分
System.out.printf("Si(%4.2f)=%12.7f\n",1000.0,lsinn(1000.0));//正弦积分
if(true)
{
int i,j,k,N;
double pr[],pi[],fr[],fi[],sr,si;
System.out.printf("请输入N:");
Scanner in = new Scanner(System.in);
N = in.nextInt();
//BufferedReader b1=new BufferedReader(new InputStreamReade(System.in));
//N=Int.parseInt(b1.readLine());
pr=new double[N];
pi=new double[N];
fr=new double[N];
fi=new double[N];
for (i=0; i<N;i++)
{
pr[i]=in.nextDouble();
pi[i]=0;
}
System.out.printf("test and verify:\n");
DFT1(pr,pi,fr,fi,N,1);
DFT1(pr,pi,fr,fi,N,-1);
}
}
}
==============================================================
【程序55】Quaternion.java
/*************************************************************************
* Compilation: javac Quaternion.java
* Execution: java Quaternion
*
* Data type for quaternions.
*
* http://mathworld.wolfram.com/Quaternion.html
*
* The data type is "immutable" so once you create and initialize
* a Quaternion, you cannot change it.
*
* % java Quaternion
*
*************************************************************************/
/*
c:\>javac Quaternion.java
c:\>java Quaternion
a = 3.0 + 1.0i + 0.0j + 0.0k
b = 0.0 + 5.0i + 1.0j + -2.0k
norm(a) = 3.1622776601683795
conj(a) = 3.0 + -1.0i + -0.0j + -0.0k
a + b = 3.0 + 6.0i + 1.0j + -2.0k
a * b = -5.0 + 15.0i + 5.0j + -5.0k
b * a = -5.0 + 15.0i + 1.0j + -7.0k
a / b = 0.5 + 1.5i + 0.09999999999999998j + -0.7k
a^-1 = 0.3 + -0.1i + -0.0j + -0.0k
a^-1 * a = 0.9999999999999999 + -5.551115123125783E-17i + 0.0j + 0.0k
a * a^-1 = 0.9999999999999999 + -5.551115123125783E-17i + 0.0j + 0.0k
*/
public class Quaternion {
private final double x0, x1, x2, x3;
// create a new object with the given components
public Quaternion(double x0, double x1, double x2, double x3) {
this.x0 = x0;
this.x1 = x1;
this.x2 = x2;
this.x3 = x3;
}
// return a string representation of the invoking object
public String toString() {
return x0 + " + " + x1 + "i + " + x2 + "j + " + x3 + "k";
}
// return the quaternion norm
public double norm() {
return Math.sqrt(x0*x0 + x1*x1 +x2*x2 + x3*x3);
}
// return the quaternion conjugate
public Quaternion conjugate() {
return new Quaternion(x0, -x1, -x2, -x3);
}
// return a new Quaternion whose value is (this + b)
public Quaternion plus(Quaternion b) {
Quaternion a = this;
return new Quaternion(a.x0+b.x0, a.x1+b.x1, a.x2+b.x2, a.x3+b.x3);
}
// return a new Quaternion whose value is (this * b)
public Quaternion times(Quaternion b) {
Quaternion a = this;
double y0 = a.x0*b.x0 - a.x1*b.x1 - a.x2*b.x2 - a.x3*b.x3;
double y1 = a.x0*b.x1 + a.x1*b.x0 + a.x2*b.x3 - a.x3*b.x2;
double y2 = a.x0*b.x2 - a.x1*b.x3 + a.x2*b.x0 + a.x3*b.x1;
double y3 = a.x0*b.x3 + a.x1*b.x2 - a.x2*b.x1 + a.x3*b.x0;
return new Quaternion(y0, y1, y2, y3);
}
// return a new Quaternion whose value is the inverse of this
public Quaternion inverse() {
double d = x0*x0 + x1*x1 + x2*x2 + x3*x3;
return new Quaternion(x0/d, -x1/d, -x2/d, -x3/d);
}
// return a / b
public Quaternion divides(Quaternion b) {
Quaternion a = this;
return a.inverse().times(b);
}
// sample client for testing
public static void main(String[] args) {
Quaternion a = new Quaternion(3.0, 1.0, 0.0, 0.0);
System.out.println("a = " + a);
Quaternion b = new Quaternion(0.0, 5.0, 1.0, -2.0);
System.out.println("b = " + b);
System.out.println("norm(a) = " + a.norm());
System.out.println("conj(a) = " + a.conjugate());
System.out.println("a + b = " + a.plus(b));
System.out.println("a * b = " + a.times(b));
System.out.println("b * a = " + b.times(a));
System.out.println("a / b = " + a.divides(b));
System.out.println("a^-1 = " + a.inverse());
System.out.println("a^-1 * a = " + a.inverse().times(a));
System.out.println("a * a^-1 = " + a.times(a.inverse()));
}
}
==============================================================
【程序56】Sort.java
//package com.yunix.shellSort;
/*
c:\>javac Sort.java
c:\>java Sort
93 10 82 28 64 52 12 71 31 19 49 72 62 55 15 5 12 46 10 2 66 17 24 91 15 44 97 5
7 21 92 63 59 19 6 34 67 49 9 60 67 2 62 9 52 17 5 65 65 25 31
2 2 5 5 6 9 9 10 10 12 12 15 15 17 17 19 19 21 24 25 28 31 31 34 44 46 49 49 52
52 55 57 59 60 62 62 63 64 65 65 66 67 67 71 72 82 91 92 93 97
MATHLIB72.DLL中的_prshl@8
2.0 5.0 4.0 1.0 6.0 8.0 3.0 7.0 9.0 0.0
0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0
*/
import java.util.Random;
public class Sort {
/**
* 希尔排序也是一种插入排序方法,实际上是一种分组插入方法
* 先取一个小于n的整数d1作为一个增量,把表的全部记录分成d1个组,所有
* 距离为d1的倍数的记录放在同一个组中,在各组内进行直接插入排序,然后
* ,取第二个增量d2(<d1),重复上述的分组和排序,直至所取的dt=1,即所有
* 记录放在同一组中进行直接插入排序为止
*/
public static int[] shellSort(int []R){
int gap = R.length/2;
int temp;
while(gap>0){
for(int i=gap;i<R.length;i++){
temp = R[i];
int j = i - gap;
while(j>=0 && temp < R[j]){
R[j+gap] = R[j];
j = j - gap;
}
R[j+gap] = temp;
}
gap = gap/2;
}
return R;
}
/*
希尔升序排序
基本思想:将整个无序序列分割成若干小的子序列分别进行插入排序。
序列分割方法:将相隔某个增量h的元素构成一个子序列。在排序过程中,逐次减小这个增量,最后当h减到1时,进行一次插入排序,排序就完成。增量序列一般采用:ht=2t-1,1≤t≤[log2n],其中n为待排序序列的长度。
*/
public static void prshl(double p[],int n)
{
int k,j,i;
double t;
k=n/2;
while(k>0)
{
for(j=k;j<=n-1;j++)
{
t=p[j];i=j-k;
while((i>=0)&&(p[i]>t))
{
p[i+k]=p[i];i=i-k;
}
p[i+k]=t;
}
k=k/2;
}
return;
}
public static void display(double[] R){
System.out.println();
for(int i=0;i<R.length;i++){
System.out.print(R[i]+" ");
}
}
public static void display(int[] R){
System.out.println();
for(int i=0;i<R.length;i++){
System.out.print(R[i]+" ");
}
}
public static void main(String[] args) {
final int M = 50;//定义数组大小为50
int []R = new int[M];
for(int i=0;i<M;i++){
R[i] = new Random().nextInt(100);//生成100以内的随机数
}
display(R);
R = shellSort(R);
display(R);
System.out.print("\nMATHLIB72.DLL中的_prshl@8");
double r[]={2,5,4,1,6,8,3,7,9,0};
display(r);
prshl(r,r.length);
display(r);
}
}
==============================================================
【程序57】Vector3f.java
/*
3D向量类,用来表示3D向量和3D点
c:\>javac Vector3f.java
c:\>java Vector3f
k=(0.0,0.0,1.0)
三维叉积的引入:向量u x v(取u,v确定平面上的垂线上的某一向量)垂直于向量u和v
定义向量u = (ux, uy, uz)和向量 v = (vx, vy, vz)的叉积运算为:u x v = (uyvz - uzvy, uzvx - uxvz, uxvy - uyvx)
反交换律:v x u = (vyuz - vzuy, vzux - vxuz, vxuy - vyux) = - (u x v)
特殊情形1:两个非零向量 a 和 b 平行,当且仅当 a × b = 0(垂直时点积为0)(u x u=0)
沿x坐标轴的向量i = (1, 0, 0)和沿y坐标轴的向量j = (0, 1, 0)的叉积为:
i x j = (1, 0, 0) x (0, 1, 0) = (0 * 0 - 0 * 1, 0 * 0 - 1 * 0, 1 * 1 - 0 * 0) = (0, 0, 1) = k
j x k = (0, 1, 0) x (0, 0, 1) = (1 * 1 - 0 * 0, 0 * 0 - 0 * 1, 0 * 0 - 0 * 0) = (1, 0, 0) = i
k x i = (0, 0, 1) x (1, 0, 0) = (0 * 0 - 1 * 0, 1 * 1 - 0 * 0, 0 * 0 - 0 * 0) = (0, 1, 0) = j
?叉乘是三维/七维等空间特有的
'定义向量u=(u_x,u_y,u_z)和向量v=(v_x,v_y,v_z)的叉积运算为:u×v=(u_yv_z-u_zv_y,u_zv_x-u_xv_z,u_xv_y-u_yv_x)
function cross(u1,u2,u3,v1,v2,v3)
cross1=u2*v3-u3v2
cross2=u3*v1-u1v3
cross3=u1*v2-u2v1
cross="(" & cross1 & "," & cross2 & "," & cross3 & ")"
end function
'i×j = k,j×k = i,k×i = j
msgbox "i×j=" & cross(1,0,0,0,1,0)
msgbox "j×k=" & cross(0,1,0,0,0,1)
msgbox "k×i=" & cross(0,0,1,1,0,0)
function Arccos(X)
Arccos=Atn(-X/Sqr(-X*X+1))+2*Atn(1)
end function
'向量u=(u_x,u_y,u_z)和向量v=(v_x,v_y,v_z)的夹角θ=arccos[(u,v)/(‖u‖·‖v‖)],0<=θ<=pi,
function angle(u1,u2,u3,v1,v2,v3)
X=(u1*v1+u2*v2+u3*v3)/(sqr(u1*u1+u2*u2+u3*u3)*sqr(v1*v1+v2*v2+v3*v3))
angle=Arccos(X)
end function
msgbox angle(1,1,-1,0,0,-1)
msgbox Arccos(sqr(3)/3)
*/
public class Vector3f {
public float x,y,z;
/**创建一个新的3D向量(0,0,0)*/
public Vector3f() {this(0,0,0);}
/**用一个指定的Vector3D来创建一个新的Vector3D类*/
public Vector3f(Vector3f v) {this(v.x, v.y, v.z);}
/**用指定的(x,y,z)来创建一个Vector3D类*/
public Vector3f(float x, float y, float z) {this.x = x;this.y = y;this.z = z;}
/**用指定的Vector3D设置这个向量*/
public void setTo(Vector3f v) {setTo(v.x, v.y, v.z);}
/**用指定的(x,y,z)设置这个向量*/
public void setTo(float x, float y, float z) {this.x = x;this.y = y;this.z = z;}
public static Vector3f cross(Vector3f u,Vector3f v)
{
Vector3f ret=new Vector3f();
ret.x=u.y*v.z-u.z*v.y;
ret.y=u.z*v.x-u.x*v.z;
ret.z=u.x*v.y-u.y*v.x;
return ret;
}
public static void main(String[] args)
{
Vector3f i = new Vector3f(1,0,0);
Vector3f j = new Vector3f(0,1,0);
Vector3f k=cross(i,j);
System.out.println("k=("+k.x+","+k.y+","+k.z+")");
}
}
==============================================================
【程序58】AlogMath.java
public class AlogMath {
public static double avg(double[] ds) {
if (ds == null) return 0D;
if (ds.length == 0) return 0D;
double sum = 0D;
for (int i = 0; i < ds.length; i ++) {
sum += ds[i];
}
return sum / ds.length;
}
public static double stdavg(double[] ds) {
if (ds == null) return 0D;
if (ds.length == 0) return 0D;
double avg = 0D;
for (int i = 0; i < ds.length; i ++) {
avg += ds[i];
}
avg = avg / ds.length;
double sum = 0D;
for (int i = 0; i < ds.length; i ++) {
sum += (ds[i] - avg) * (ds[i] - avg);
}
sum /= ds.length;
return Math.sqrt(sum);
}
public static void main(String[] args){
double[] ds1 = {1,2,3,4,5,6,7,8,9,10};
double avg1 = AlogMath.avg(ds1);
double savg1 = AlogMath.stdavg(ds1);
double[] ds2 = {4,1,0,2,1,5,1,3,4,3};
double avg2 = AlogMath.avg(ds2);
double savg2 = AlogMath.stdavg(ds2);
System.out.println("平均数为:"+avg1);
System.out.println("标准差为:"+savg1);
System.out.println("平均数为:"+avg2);
System.out.println("标准差为:"+savg2);
}
}
==============================================================
【程序59】IsLeapYear.java
/*
c:\>javac IsLeapYear.java//此时大小写不敏感
c:\>java IsLeapYear//此时大小写敏感
*/
public class IsLeapYear{
public static int IsLeapYear( int year )
{
if ((year %4 == 0) && (year % 100 != 0) ||
(year % 400 == 0) )
return 1;
else
return 0;
}
public static void main(String args[]){
IsLeapYear j1=new IsLeapYear();
int year=2014;
int temp=2;
if( IsLeapYear(year)==1 && (temp == 2))
{
}
else
{
System.out.printf("不是闰年的2月\n");
}
}
}
Birthday1.java
public class Birthday1
{
private int year;
private int month;
private int day;
public Birthday1(int y, int m, int d)
{
year = y;
month = m;
day = d;
}
public void isLeapYear()
{
boolean leapyear = ((year % 400 == 0) || (year % 100 != 0 && year % 4 == 0)) ? true : false;
System.out.println("您所输入的年份是闰年吗?" + (leapyear ? "是" : "不是"));
}
public static void main(String[] args)
{
Birthday1 Bri1 = new Birthday1(1986, 10, 7);
Bri1.isLeapYear();
}
}
Birthday.java
public class Birthday
{
int year;
int month;
int day;
public Birthday(int y, int m, int d)
{
year = y;
month = m;
day = d;
}
public void isLeapYear()
{
boolean leapyear = false;
if (this.year % 100 == 0 && this.year % 400 == 0)
{
leapyear = true;
}
else if (this.year % 4 == 0)
{
leapyear = true;
}
System.out.println("您所输入的年份是闰年吗?" + leapyear);
}
public static void main(String[] args)
{
Birthday Bri1 = new Birthday(2000, 10, 7);
Bri1.isLeapYear();
}
}
==============================================================
【程序60】Complex.java
/*************************************************************************
* Compilation: javac Complex.java
* Execution: java Complex
*http://introcs.cs.princeton.edu/java/97data/Complex.java.html
* Data type for complex numbers.
*
* The data type is "immutable" so once you create and initialize
* a Complex object, you cannot change it. The "final" keyword
* when declaring re and im enforces this rule, making it a
* compile-time error to change the .re or .im fields after
* they've been initialized.
*
* % java Complex
* a = 5.0 + 6.0i
* b = -3.0 + 4.0i
* Re(a) = 5.0
* Im(a) = 6.0
* b + a = 2.0 + 10.0i
* a - b = 8.0 + 2.0i
* a * b = -39.0 + 2.0i
* b * a = -39.0 + 2.0i
* a / b = 0.36 - 1.52i
* (a / b) * b = 5.0 + 6.0i
* conj(a) = 5.0 - 6.0i
* |a| = 7.810249675906654
* tan(a) = -6.685231390246571E-6 + 1.0000103108981198i
*
*************************************************************************/
public class Complex {
private final double re; // the real part
private final double im; // the imaginary part
// create a new object with the given real and imaginary parts
public Complex(double real, double imag) {
re = real;
im = imag;
}
// return a string representation of the invoking Complex object
public String toString() {
if (im == 0) return re + "";
if (re == 0) return im + "i";
if (im < 0) return re + " - " + (-im) + "i";
return re + " + " + im + "i";
}
// return abs/modulus/magnitude and angle/phase/argument
public double abs() { return Math.hypot(re, im); } // Math.sqrt(re*re + im*im)
public double phase() { return Math.atan2(im, re); } // between -pi and pi
// return a new Complex object whose value is (this + b)
public Complex plus(Complex b) {
Complex a = this; // invoking object
double real = a.re + b.re;
double imag = a.im + b.im;
return new Complex(real, imag);
}
// return a new Complex object whose value is (this - b)
public Complex minus(Complex b) {
Complex a = this;
double real = a.re - b.re;
double imag = a.im - b.im;
return new Complex(real, imag);
}
// return a new Complex object whose value is (this * b)
public Complex times(Complex b) {
Complex a = this;
double real = a.re * b.re - a.im * b.im;
double imag = a.re * b.im + a.im * b.re;
return new Complex(real, imag);
}
// scalar multiplication
// return a new object whose value is (this * alpha)
public Complex times(double alpha) {
return new Complex(alpha * re, alpha * im);
}
// return a new Complex object whose value is the conjugate of this
public Complex conjugate() { return new Complex(re, -im); }
// return a new Complex object whose value is the reciprocal of this
public Complex reciprocal() {
double scale = re*re + im*im;
return new Complex(re / scale, -im / scale);
}
// return the real or imaginary part
public double re() { return re; }
public double im() { return im; }
// return a / b
public Complex divides(Complex b) {
Complex a = this;
return a.times(b.reciprocal());
}
// return a new Complex object whose value is the complex exponential of this
public Complex exp() {
return new Complex(Math.exp(re) * Math.cos(im), Math.exp(re) * Math.sin(im));
}
// return a new Complex object whose value is the complex sine of this
public Complex sin() {
return new Complex(Math.sin(re) * Math.cosh(im), Math.cos(re) * Math.sinh(im));
}
// return a new Complex object whose value is the complex cosine of this
public Complex cos() {
return new Complex(Math.cos(re) * Math.cosh(im), -Math.sin(re) * Math.sinh(im));
}
// return a new Complex object whose value is the complex tangent of this
public Complex tan() {
return sin().divides(cos());
}
// a static version of plus
public static Complex plus(Complex a, Complex b) {
double real = a.re + b.re;
double imag = a.im + b.im;
Complex sum = new Complex(real, imag);
return sum;
}
// sample client for testing
public static void main(String[] args) {
Complex a = new Complex(5.0, 6.0);
Complex b = new Complex(-3.0, 4.0);
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("Re(a) = " + a.re());
System.out.println("Im(a) = " + a.im());
System.out.println("b + a = " + b.plus(a));
System.out.println("a - b = " + a.minus(b));
System.out.println("a * b = " + a.times(b));
System.out.println("b * a = " + b.times(a));
System.out.println("a / b = " + a.divides(b));
System.out.println("(a / b) * b = " + a.divides(b).times(b));
System.out.println("conj(a) = " + a.conjugate());
System.out.println("|a| = " + a.abs());
System.out.println("tan(a) = " + a.tan());
}
}
Book.java
import java.io.*;
public class Book{
double sb;
double xb;
Book(double x,double y){
this.sb=x;
this.xb=y;
}
Book(){
}
public static void main(String args[]){
System.out.println("请输入数据:");
double a=0;
double b=0;
double c=0;
double d=0;
String s;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入第一个复数的实部:");
try{
s = in.readLine();
a=Double.parseDouble(s);
}
catch(IOException e)
{ System.out.println("抛掷异常");}
System.out.println("请输入第一个复数的虚部:");
try{
s = in.readLine();
b =Double.parseDouble(s);
}
catch(IOException e)
{ System.out.println("抛掷异常");}
System.out.println("请输入第二个复数的实部:");
try{
s = in.readLine();
c =Double.parseDouble(s);
}
catch(IOException e)
{ System.out.println("抛掷异常");}
System.out.println("请输入第二个复数的虚部:");
try{
s = in.readLine();
d =Double.parseDouble(s);
}
catch(IOException e)
{ System.out.println("抛掷异常");}
Book h;
h=new Book(a,b);
Book j;
j=new Book(c,d);
System.out.println("您输入的一个数为:");
toString(h);
System.out.println("您输入的二个数为:");
toString(j);
Book k;
k=new Book();
char z='y';
do{
System.out.println("请选择您要进行的计算:");
System.out.println("1 :进行加法运算");
System.out.println("2 :进行减法运算");
System.out.println("3 :进行修改");
System.out.println("4 :进行乘法运算");
System.out.println("5 :进行除法运算");
System.out.println("6 :查看修改结果");
int i=0;
try{
i= Integer.parseInt(in.readLine());
}
catch(IOException e)
{ System.out.println("抛掷异常");}
switch(i)
{
case 1:
k.sb=jia(h.sb,j.sb);
k.xb=jia(h.xb,j.xb);
System.out.println("计算结果的实部为:"+k.sb);
System.out.println("计算结果的虚部为:"+k.xb);
toString(k);
break ;
case 2:
k.sb=jian(h.sb,j.sb);
k.xb=jian(h.xb,j.xb);
System.out.println("计算结果的实部为:"+k.sb);
System.out.println("计算结果的虚部为:"+k.xb);
toString(k);
break ;
case 3:
System.out.println("请输入您要修改哪个实数:");
int l=0;
try{
l= Integer.parseInt(in.readLine());
}
catch(IOException e)
{ System.out.println("抛掷异常");}
if(l==1)
{
h.xiugais(h);
h.xiugaix(h);
}
else
{
xiugais(j);
xiugaix(j);
}
break ;
case 4:
double f=0;
double e=0;
f=cheng(h.sb,j.sb)+cheng(h.xb,j.xb);
e=cheng(h.sb,j.xb)+cheng(h.xb,j.sb);
k.sb=(double)(Math.round(f*100)/100.0);
k.xb=(double)(Math.round(e*100)/100.0);
System.out.println("计算结果的实部为:"+k.sb);
System.out.println("计算结果的虚部为:"+k.xb);
toString(k);
break ;
case 5:
double chushu=cheng(j.sb,j.sb)-cheng(j.xb,-j.xb);
double beichushus=jian(cheng(h.sb,j.sb),cheng(h.xb,-j.xb));
double beichushux=jia(cheng(h.sb,-j.xb),cheng(h.xb,j.sb));
k.sb=chu(beichushus,chushu);
k.xb=chu(beichushux,chushu);
System.out.println("计算结果的实部为:"+k.sb);
System.out.println("计算结果的虚部为:"+k.xb);
toString(k);
break ;
case 6:
System.out.println("修改后的结果为:");
System.out.println("第一个复数:"+toString(h));
System.out.println("第二个复数:"+toString(j));
break ;
}
System.out.println("请问您是否还要继续 y/n:");
try{
z=(char)System.in.read();
System.in.skip(2); //忽略回车换行
}
catch(IOException e){}
} while(z=='y');
}
public static double gets(Book a){
return a.sb;
}
public static double getx(Book b){
return b.xb;
}
public static double xiugais(Book a)
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入您要修改的实部:");
double m=0;
try{
m= Double.parseDouble(in.readLine());
}
catch(IOException e)
{ System.out.println("抛掷异常");}
a.sb=m;
System.out.println("修改成功:");
return 0;
}
public static double xiugaix(Book b)
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入您要修改的虚部:");
double n=0;
try{
n= Double.parseDouble(in.readLine());
}
catch(IOException e)
{ System.out.println("抛掷异常");}
b.xb=n;
System.out.println("修改成功:");
return 0;
}
public static double jia(double a,double b)//
{
double c=0;
c=a+b;
System.out.println("加法成功:");
return c ;
}
public static double jian(double a,double b)
{
double c=0;
c=a-b;
System.out.println("减法成功:");
return c;
}
public static double cheng(double a,double b)
{
double c=0;
c=a*b;
System.out.println("乘法成功:");
return c;
}
public static double chu(double a,double b)
{
double d=0;
double c=0;
d=a/b;
c=(double)(Math.round(d*100)/100.0);
System.out.println("除法成功:");
return c ;
}
public static double toString(Book a){
System.out.println("结果为:"+a.sb+"+"+a.xb+"*i");
return 0;
}
}
==============================================================
【程序64】DefiniteIntegral.java
import static java.lang.Math.*;
public class DefiniteIntegral {
// 0~1区间n等分
private static int n = 100000;
// 随便定义个曲线e的x次方, 取其x在0~1的定积分;
public static double f(double x) {
double f;
f = pow(E, x);
return f;
}
// 梯形法求定积分
/**
* x0: 坐标下限, xn: 坐标上限
*/
public static double getDefiniteIntegralByTrapezium(double x0, double xn) {
double h = abs(xn - x0) / n;
double sum = 0;
for (double xi = 0; xi <= xn; xi = xi + h) {
sum += (f(xi) + f(xi + h)) * h / 2;
}
return sum;
}
/**
* x0: 坐标下限, xn: 坐标上限
*/
// 矩形法求定积分, 右边界
public static double getDefiniteIntegralByRectangle1(double x0, double xn) {
//h: 步长
double h = abs(xn - x0) / n;
double sum = 0;
for (double xi = 0; xi <= xn; xi = xi + h) {
sum += f(xi + h) * h;
}
return sum;
}
// 矩形法求定积分, 左边界
public static double getDefiniteIntegralByRectangle2(double x0, double xn) {
double h = abs(xn - x0) / n;
double sum = 0;
for (double xi = 0; xi <= xn; xi = xi + h) {
sum += f(xi) * h;
}
return sum;
}
/**
* 测试定积分
*/
public static void main(String[] args) {
System.out.println(getDefiniteIntegralByTrapezium(0, 1));
System.out.println(getDefiniteIntegralByRectangle1(0, 1));
System.out.println(getDefiniteIntegralByRectangle2(0, 1));
}
}
==============================================================
【程序65】Factorial.java
/*
*Factorial.java
*/
public class Factorial
{
private long result=1;
public Factorial()
{ this(0); }
public Factorial(int n)
{ for(int i=2;i<=n;i++)
{ result*=i; }
System.out.println(n+"!="+result); }
public static void main(String[] args)
{ for(int i=0;i<=30;i+=1)
{ Factorial myFactorial=new Factorial(i); }
}}
==============================================================
【程序66】Gamma.java
public class Gamma {
static double gamma(double x){
int i;
double y,t,s,u;
final double a[] ={0.0000677106, -0.0003442342,
0.0015397681, -0.0024467480,
0.0109736958, -0.0002109075,
0.0742379071, 0.0815782188,
0.4118402518, 0.4227843370,
1.0};
if (x<=0.0){
System.out.println("error x<=0!\n");
return -1.0;
}
y=x;
if (y<=1.0){
t=1.0/(y*(y+1.0));
y=y+2.0;
}
else if (y<=2.0){
t=1.0/y;
y=y+1.0;
}
else if (y<=3.0){
t=1.0;
}
else{
t=1.0;
while(y>3.0){
y=y-1.0;
t=t*y;
}
}
s=a[0];
u=y-2.0;
for (i=1; i<=10; i++){
s=s*u+a[i];
}
s=s*t;
return(s);
}
public static void main(String[] args) {
double x = gamma(0.50);
System.out.println(x);//1.7724540592304685
x = gamma(1.00);
System.out.println(x);//
x = gamma(2.00);
System.out.println(x);//
x = gamma(3.00);
System.out.println(x);//
}
}
==============================================================
【程序67】MathTool.java
import java.math.BigDecimal;
public class MathTool {
/*
* 加法运算
*/
public static String jia(double d1,double d2){
BigDecimal b1 = new BigDecimal(d1+"");
BigDecimal b2 = new BigDecimal(d2+"");
return b1.add(b2).toPlainString();
}
/*
* 减法运算
*/
public static String jian(double d1,double d2){
BigDecimal b1 = new BigDecimal(d1+"");
BigDecimal b2 = new BigDecimal(d2+"");
return b1.subtract(b2).toPlainString();
}
/*
* 乘法运算
*/
public static String cheng(double d1,double d2){
BigDecimal b1 = new BigDecimal(d1+"");
BigDecimal b2 = new BigDecimal(d2+"");
return b1.multiply(b2).toPlainString();
}
/*
* 除法运算
*/
public static String chu(double d1,double d2,int point){
BigDecimal b1 = new BigDecimal(d1+"");
BigDecimal b2 = new BigDecimal(d2+"");
return b1.divide(b2,point,BigDecimal.ROUND_HALF_UP).toPlainString();
}
public static void main(String[] args) {
double double_a = 0.05d;
double double_b = 0.01d;
System.out.println(MathTool.jia(double_a, double_b));//0.06
System.out.println(MathTool.jian(double_a, double_b));//0.04
System.out.println(MathTool.cheng(double_a, double_b));//0.0005
System.out.println(MathTool.chu(double_a, double_b,0));//5
}
}
Test1.java
import java.math.BigDecimal;
public class Test1 {
public static void main(String[] args) {
double x = Math.log(5);
System.out.println(x);//1.6094379124341003
double x1 = Math.log10(5);
System.out.println(x1);//0.6989700043360189
System.out.println(3/2);//1
float float_a = 0.05f;
float float_b = 0.01f;
System.out.println(float_a+float_b);//0.060000002
double double_a = 0.05d;
double double_b = 0.01d;
System.out.println(double_a+double_b);//0.060000000000000005
BigDecimal bigDecimal_a1 = new BigDecimal(float_a+"");
BigDecimal bigDecimal_b1 = new BigDecimal(float_b+"");
System.out.println(bigDecimal_a1.add(bigDecimal_b1));//0.06
BigDecimal bigDecimal_a2 = new BigDecimal(double_a+"");
BigDecimal bigDecimal_b2 = new BigDecimal(double_b+"");
System.out.println(bigDecimal_a2.add(bigDecimal_b2));//0.06
}
}
==============================================================
【程序68】Matrix.java
import java.util.*;
class Matrix{
public static void main(String[] args)
{
Matrix m1 = new Matrix();
Matrix m2 = new Matrix();
int operation;
Scanner r = new Scanner(System.in);
m1.In();
m2.In();
System.out.print("请选择运算方法(1表示加法,2表示乘法):");
operation = r.nextInt();
if (operation == 1){
System.out.println("结果是:");
m1.Add(m2).Show();
}
else if (operation == 2){
System.out.println("结果是:");
m1.Multi(m2).Show(); }
else{
System.out.println("Error: No such operation."); } }
Matrix(){
cols = rows = 0;
mat = null; }
Matrix(int c, int r, double[][] elem)
{
cols = c;
rows = r;
mat = Arrays.copyOf(elem, elem.length); }
Matrix Add(Matrix m){
if (this.cols != m.cols || this.rows != m.rows)
{
System.out.println("Error: Cannot add.");
return new Matrix(); }
double[][] result = new double[this.cols][this.rows];
for (int c = 0; c < result.length; c++){
for (int r = 0; r < result[c].length; r++){
result[c][r] += this.mat[c][r] + m.mat[c][r]; } }
return new Matrix(this.cols, this.rows, result); }
Matrix Multi(Matrix m){
if (this.rows != m.cols){
System.out.println("Error: Cannot multiply.");
return new Matrix(); }
double[][] result = new double[this.cols][m.rows];
for (int c = 0; c < result.length; c++)
{
Arrays.fill(result[c], 0);
for (int r = 0; r < result[c].length; r++)
{
for (int i = 0; i < this.rows; i++){
result[c][r] += this.mat[c][i] * m.mat[i][r]; } } }
return new Matrix(this.cols, m.rows, result); }
void In()
{
Scanner s = new Scanner(System.in);
_in++;
System.out.println("请输入第" + _in + "个矩阵的行数:");
this.cols = s.nextInt();
System.out.println("请输入第" + _in + "个矩阵的列数:");
this.rows = s.nextInt();
this.mat = new double[this.cols][this.rows];
System.out.println("请依次输入第" + _in + "个矩阵的元素:");
for (int c = 0; c < this.cols; c++){
for (int r = 0; r < this.rows; r++){
this.mat[c][r] = s.nextDouble(); } } }
void Show(){
if (mat == null){
//System.out.println("Error: No such matrix.");
return;
}
for (double[] c : this.mat)
{
System.out.print("|");
for (double r : c){
System.out.print(" " + r + " ");
}
System.out.println("|");
} }
int cols, rows;
double[][] mat;
static int _in = 0;
}
==============================================================
【程序69】Str.java
public class Str{
//Java语言内部的char是使用UTF-16,所以都是两字节。
//getBytes后,实际上是转换成指定的编码字符集。
//不指定时,一般用本地字符集,通常是GBK、ACSII等,在这些字符集中,英文都是单字节的
public static void main(String[] args) {
String s1="cn";
String s2="中国";
String s3="我们C/C++ Tips";
System.out.println(s1.length());//2
System.out.println(s2.length());//2
System.out.println(s3.length());//12
System.out.println(s1.getBytes().length);//2
System.out.println(s2.getBytes().length);//4
System.out.println(s3.getBytes().length);//14
System.out.printf("%s contains %d characters\n",s3, s3.length());
}
}
==============================================================
【程序72】RootsOfUnity.java
class Complex implements Cloneable{
Complex(double re, double im);
double re();
double im();
Complex mult(Comlex rhs);
public Object clone();
public String toString();
}
class Complex implements Cloneale{
private double re, im;
Complex(double re, double im){
this.re = re;
this.im = im;
}
double re(){
return re;
}
double im(){
return im;
}
void add(Complex rhs){
re = re() + rhs.re();
im = im() + rhs.im();
}
void mult(Complex rhs){
double t = re();
re = re() * rhs.re() - im() * rhs.im();
im = t * rhs.im() + im() * rhs.re();
}
public String toString(){
return re() + " " + im();
}
}
public class RootsOfUnity{
public static void main(String args[]){
int N = 100;
System.out.println(N + " roots of unity.");
for(int k = 0; k < N; k++){
double x = Math.cos(2.0 * Math.PI * k / N);
double y = Math.sin(2.0 * Math.PI * k / N);
Complex c = new Complex(x,y);
System.out.println(k + " : " + c);
Complex z = (Complex)c.clone();
for(int j = 0; j < N-1; j++){
z.mult(c);
}
System.out.println(" " + z);
}
}
}
==============================================================
【程序73】month.java
/*
C:\>javac month.java
C:\>java month
January(31)
February(28)
March(31)
April(30)
May(31)
June(30)
July(31)
August(31)
September(30)
October(31)
November(30)
December(31)
*/
public class month
{
public static void main(String args[])
{
int month_day[]={31,28,31,30,31,30,31,31,30,31,30,31,29};
int len=month_day.length;
for(int temp = 1; temp <=len; temp++ )
{
switch( temp )
{
case 1:
System.out.printf(" January(%d)\n",month_day[temp-1]);
break;
case 2:
System.out.printf(" February(%d)\n",month_day[temp-1]);
break;
case 3:
System.out.printf(" March(%d)\n",month_day[temp-1]);
break;
case 4:
System.out.printf(" April(%d)\n",month_day[temp-1]);
break;
case 5:
System.out.printf(" May(%d)\n",month_day[temp-1]);
break;
case 6:
System.out.printf(" June(%d)\n",month_day[temp-1]);
break;
case 7:
System.out.printf(" July(%d)\n",month_day[temp-1]);
break;
case 8:
System.out.printf(" August(%d)\n",month_day[temp-1]);
break;
case 9:
System.out.printf(" September(%d)\n",month_day[temp-1]);
break;
case 10:
System.out.printf(" October(%d)\n",month_day[temp-1]);
break;
case 11:
System.out.printf(" November(%d)\n",month_day[temp-1]);
break;
case 12:
System.out.printf(" December(%d)\n",month_day[temp-1]);
break;
}
}
}
}
==============================================================
【程序74】NumberTheory.java
/*
C:\>javac NumberTheory.java
C:\>java NumberTheory
最大公约数:8
最小公倍数:56
*/
public class NumberTheory{
public static void main(String args[]) {
int i = 56;
int j = 8;
System.out.println("最大公约数:" + NumberTheory.gcd(i, j));
System.out.println("最大公约数:" + NumberTheory.GCD(i, j));
System.out.println("最小公倍数:" + NumberTheory.lcm(i, j));
}
// 得到最大公约数
public static int gcd(int x, int y) {
int temp;
while (x != 0) {
temp = x;
x = y % x;
y = temp;
}
return y;
}
//求2个数的最大公约数
public static int GCD(int a, int b)
{
if(a*b<0)
return -GCD(Math.abs(a),Math.abs(b));
int temp=0;
if(a<b)
{
temp=a;
a=b;
b=temp;
}
if(a%b==0)
return b;
else
return GCD(a%b,b);
//return 0;
}
// 得到最小公倍数
public static int lcm(int x, int y) {
return (x*y)/gcd(x,y);
}
}
==============================================================
【程序75】VectorDemo.java
import java.util.*;
/*
演示Vector的使用。包括Vector的创建、向Vector中添加元素、从Vector中删除元素、 统计Vector中元素的个数和遍历Vector中的元素。
C:\>javac VectorDemo.java
注意:VectorDemo.java 使用了未经检查或不安全的操作。
注意:要了解详细信息,请使用 -Xlint:unchecked 重新编译。
C:\>java VectorDemo
size:3
Test0
Test2
Test2
C:\>java VectorDemo
abc
bcd
=================================
1--a
1--b
2--c
*/
public class VectorDemo
{
public static void main(String[] args){
Vector vc = new Vector();
vc.add(0, "abc");
vc.add(1, "bcd");
for (int i = 0; i < vc.size(); i++)
{
System.out.println(vc.get(i));
}
System.out.println("=================================");
Vector data = new Vector();
List list = new ArrayList();
list.add("1--a");
list.add("1--b");
data.add(list);
data.add("2--c");
for (int i = 0; i < data.size(); i++)
{
if(i==0)
{
List d1 = (List) (data.get(i));
for (int j = 0; j < d1.size(); j++)
{
System.out.println(d1.get(j));
}
}
else
{
System.out.println(data.get(i));
}
}
}
public static void main1(String[] args)
{
//Vector的创建
//使用Vector的构造方法进行创建
Vector v = new Vector(4);
//向Vector中添加元素
//使用add方法直接添加元素
v.add("Test0");
v.add("Test1");
v.add("Test0");
v.add("Test2");
v.add("Test2");
//从Vector中删除元素
v.remove("Test0");
//删除指定内容的元素
v.remove(0);
//按照索引号删除元素
//获得Vector中已有元素的个数
int size = v.size();
System.out.println("size:" + size);
//遍历Vector中的元素
for(int i = 0;i < v.size();i++)
{
System.out.println(v.get(i));
}
}
}
==============================================================
【程序76】VectorDemo2.java
/*
javac VectorDemo2.java
java VectorDemo2
φ(2)=1,模2的既约剩余类:
1
φ(4)=2,模4的既约剩余类:
1
3
φ(8)=4,模8的既约剩余类:
1
3
5
7
φ(16)=8,模16的既约剩余类:
1
3
5
7
9
11
13
15
*/
import java.util.*;
public class VectorDemo2
{
// 求2个数的最大公约数
public static int GCD(int a, int b)
{
if(a*b<0)
return -GCD(Math.abs(a),Math.abs(b));
int temp=0;
if(a<b)
{
temp=a;
a=b;
b=temp;
}
if(a%b==0)
return b;
else
return GCD(a%b,b);
}
public static int Iscoprime(int a, int b)
{
int ret=0;
if(GCD(a,b)==1)
ret=1;
return ret;
}
public static Vector totientEx(int num)
{
Vector v = new Vector();
if(num==1)
{
v.add(1);
return v;
}
for(int i=1;i<=num-1;i++)
{
if(Iscoprime(num,i)==1)
{
v.add(i);
}
}
return v;
}
public static void main(String[] args)
{
int Arr[]={2,4,8,16};
for(int i=0;i<4;i++)
{
int n=Arr[i];
Vector v = totientEx(n);
int size = v.size();
System.out.printf("φ(%d)=%d,模%d的既约剩余类:\n",n,size,n);
//遍历Vector中的元素
for(int j = 0;j < v.size();j++)
{
System.out.println(v.get(j));
}
}
}
}
==============================================================
【程序77】rgb.java
/*
C:\>javac rgb.java
C:\>java rgb
rgb16=-1024=FC00=1111110000000000
rgb16=31744=7C00=111110000000000
*/
public class rgb{
/*
5.5.5格式,最高位为Alpha位,表示是不是透明,其余15位表示颜色,红绿蓝各5位,这种格式可以表示32786种颜色。
*/
//#define _RGB16BIT555(r,g,b)((b%32)+((g%32)<<5)+((r%32)<<10))
//public static short RGB16BIT555(byte r,byte g,byte b)
public static short RGB16BIT555(short r,short g,short b)
{
return (short)((b%32)+((g%32)<<5)+((r%32)<<10));
}
public static void main(String args[])
{
//short rgb16=RGB16BIT555((byte)255,(byte)0,(byte)0);
short rgb16=RGB16BIT555((short)255,(short)0,(short)0);
System.out.println("rgb16="+rgb16);
}
}
==============================================================
【程序78】rtcStr.java
/*
C:\>javac rtcStr.java
C:\>java rtcStr
a输入为:
hanxiao
b输入为:
oaixnah
a=hanxiao
b=oaixnah
c=oaixnah
c=b
C:\>javac rtcStr.java
C:\>java rtcStr
a输入为:
mn
b输入为:
nm
a=mn
b=nm
c=nm
c=b
*/
import java.io.*;
public class rtcStr{
public static void main(String args[])throws IOException
{
String a=new String();
String b=new String();
System.out.println("a输入为:");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
a = br1.readLine();
System.out.println("b输入为:");
BufferedReader br2 = new BufferedReader(new InputStreamReader(System.in));
b = br2.readLine();
StringBuffer aa=new StringBuffer(a);
StringBuffer cc=aa.reverse();
String c;//=new String();
c=cc.toString();
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("c="+c);
if(c.equals(b)==true)
{System.out.println("c=b");}
else
{System.out.println("c<>b");}
}
}
==============================================================
【程序79】jacobiN.java
/*
c:\>javac jacobiN.java
c:\>java jacobiN
*/
public class jacobiN{
/*
按定义计算二次剩余和二次非剩余
x=8,(13/17)=1
x=无解,(5/17)=-1
*/
public static int Legendre(int a,int p)
{
if(a%p==0)
return 0;//a是p的倍数
for(int i=1;i<p;i++)
{
if((i*i-a)%p==0)
{
return 1;//a是p的二次剩余
}
}
return -1;//a是p的二次非剩余
}
public static int Gauss(int a,int p)
{
if(a%p==0)
return 0;//a是p的倍数
for(int i=1;i<p;i++)
{
if((i*i*i*i-a)%p==0)
{
return 1;//a是p的四次剩余
}
}
return -1;//a是p的四次非剩余
}
public static int Eisenstein(int a,int p)
{
if(a%p==0)
return 0;//a是p的倍数
for(int i=1;i<p;i++)
{
if((i*i*i-a)%p==0)
{
return 1;//a是p的三次剩余
}
}
return -1;//a是p的三次非剩余
}
public static void main(String args[]){
jacobiN j1=new jacobiN();
/*
{
int a[]={13,5};
int p=17;
for(int i=0;i<2;i++)
{
int ret=Legendre(a[i],p);
System.out.printf("jacobi(%d,%d)=%d\n",a[i],p,ret);
}
}
{
int a[]={1,2,3,4,7,8};
int p=5;
for(int i=0;i<6;i++)
{
int ret=Legendre(a[i],p);
System.out.printf("jacobi(%d,%d)=%d\n",a[i],p,ret);
}
}
{
int a[]={13,5};
int p=17;
for(int i=0;i<2;i++)
{
int ret=Gauss(a[i],p);
System.out.printf("jacobi4(%d,%d)=%d\n",a[i],p,ret);
}
}
{
int a[]={1,2,3,4,7,8};
int p=5;
for(int i=0;i<6;i++)
{
int ret=Gauss(a[i],p);
System.out.printf("jacobi4(%d,%d)=%d\n",a[i],p,ret);
}
}
{
int a[]={13,5};
int p=17;
for(int i=0;i<2;i++)
{
int ret=Eisenstein(a[i],p);
System.out.printf("jacobi3(%d,%d)=%d\n",a[i],p,ret);
}
}
*/
{
int a[]={-7};
int p[]={-3};
for(int i=0;i<1;i++)
for(int j=0;j<1;j++)
{
int ret=Legendre(a[i],p[j]);
System.out.printf("jacobi(%d,%d)=%d\n",a[i],p[j],ret);
int ret1=Gauss(a[i],p[j]);
System.out.printf("jacobi4(%d,%d)=%d\n",a[i],p[j],ret1);
}
}
}
}
==============================================================
【程序80】Polynomial.java
import java.util.*;
import java.math.*;
/**
Polynomials over a field. Polynomials are immutable.
*/
class Polynomial {
// field of coefficients
private final Field field;
// little endian (coeff[0] + coeff[1] * x + coeff[2] * x^2 ...)
// the last coefficient must be non-zero.
private final FieldElem[] coeff;
private Polynomial(FieldElem[] coeff, Field field) {
this.field = field;
// remove leading zeroes
int len = 0;
for (int i = coeff.length - 1; i >= 0; i--) {
if (!coeff[i].equals(field.zero)) {
len = i + 1;
break;
}
}
if (len < coeff.length) {
FieldElem[] new_coeff = new FieldElem[len];
System.arraycopy(coeff, 0, new_coeff, 0, len);
coeff = new_coeff;
}
this.coeff = coeff;
}
static Polynomial zero(Field field) {
return new Polynomial(new FieldElem[0], field);
}
static Polynomial one(Field field) {
return new Polynomial(new FieldElem[]{field.one}, field);
}
static Polynomial constant(FieldElem c, Field field) {
return new Polynomial(new FieldElem[]{c}, field);
}
static Polynomial x(Field field) {
return new Polynomial(new FieldElem[]{field.zero, field.one}, field);
}
Polynomial add(Polynomial x) {
assert x.field == field;
FieldElem[] c = new FieldElem[Math.max(coeff.length, x.coeff.length)];
for (int i = 0; i < c.length; i++) {
if (i < coeff.length) {
if (i < x.coeff.length) {
c[i] = coeff[i].add(x.coeff[i]);
} else {
c[i] = coeff[i];
}
} else {
c[i] = x.coeff[i];
}
}
return new Polynomial(c, field);
}
Polynomial sub(Polynomial x) {
return add(x.mul(field.one.neg()));
}
Polynomial mul(FieldElem x) {
FieldElem[] c = new FieldElem[coeff.length];
for (int i = 0; i < c.length; i++) {
c[i] = coeff[i].mul(x);
}
return new Polynomial(c, field);
}
Polynomial mul(Polynomial x) {
if (coeff.length == 0) return this;
if (x.coeff.length == 0) return x;
FieldElem[] c = new FieldElem[coeff.length + x.coeff.length - 1];
for (int i = 0; i < c.length; i++) c[i] = field.zero;
for (int i = 0; i < coeff.length; i++) {
for (int j = 0; j < x.coeff.length; j++) {
c[i + j] = c[i + j].add(coeff[i].mul(x.coeff[j]));
}
}
return new Polynomial(c, field);
}
// returns [this/x, this%x]
Polynomial[] div(Polynomial divisor) {
Polynomial dividend = zero(field);
Polynomial remainder = this;
while (remainder.degree() >= divisor.degree()) {
int k = remainder.degree() - divisor.degree();
// dividend += m * x^k
// remainder -= m * x^k * divisor
// choose m such that high term of remainder is cancelled
FieldElem m = remainder.lead().div(divisor.lead());
// compute z = x^k
Polynomial z = x(field).pow(k);
dividend = dividend.add(z.mul(m));
remainder = remainder.sub(z.mul(m).mul(divisor));
}
assert dividend.mul(divisor).add(remainder).equals(this);
assert remainder.degree() < divisor.degree();
return new Polynomial[]{dividend, remainder};
}
/** compute this^e */
Polynomial pow(int e) {
Polynomial x = this;
Polynomial r = one(field);
while (e > 0) {
if ((e & 1) != 0) {
r = r.mul(x); // r *= x
}
e >>= 1;
x = x.mul(x); // x = x^2 mod p
}
return r;
}
/** compute this^e mod p */
Polynomial modPow(int e, Polynomial p) {
Polynomial x = this;
Polynomial r = one(field);
while (e > 0) {
if ((e & 1) != 0) {
r = r.mul(x).div(p)[1]; // r *= x mod p
}
e >>= 1;
x = x.mul(x).div(p)[1]; // x = x^2 mod p
}
return r;
}
Polynomial modPow(BigInteger e, Polynomial p) {
Polynomial x = this;
Polynomial r = one(field);
if (e.signum() == 0) return r;
int n = e.bitLength();
for (int i = 0; i < n - 1; i++) {
if (e.testBit(i)) {
r = r.mul(x).div(p)[1]; // r *= x mod p
}
x = x.mul(x).div(p)[1]; // x = x^2 mod p
}
r = r.mul(x).div(p)[1]; // highest bit
return r;
}
/** The degree of a constant is zero, except for zero which
has a degree of -1. */
int degree() {
return coeff.length - 1;
}
FieldElem lead() {
return coeff[coeff.length - 1];
}
FieldElem tail() {
return coeff[0];
}
Polynomial monic() {
if (coeff.length == 0) return this; // 0
if (lead().equals(field.one)) return this; // already monic
return mul(lead().inv());
}
Polynomial gcd(Polynomial x) {
Polynomial a = monic();
Polynomial b = x.monic();
// a.degree() + b.degree() goes down by at least 1 in each iteration
while (true) {
// make a the one with higher (or equal) degree
if (a.degree() < b.degree()) {
Polynomial t = a;
a = b;
b = t;
}
if (b.degree() < 0) return a; // gcd(a,0) == a
// compute z = x^(a.degree() - b.degree())
Polynomial z = x(field).pow(a.degree() - b.degree());
// compute a - z*b, which is guaranteed to cancel the
// highest degree of a.
a = a.sub(b.mul(z)).monic();
}
}
/** Compute symbolic differential of the polynomial */
Polynomial diff() {
if (coeff.length == 0) return this;
FieldElem[] c = new FieldElem[coeff.length - 1];
for (int i = 1; i < coeff.length; i++) {
c[i - 1] = field.nth(i).mul(coeff[i]);
}
return new Polynomial(c, field);
}
/** Compose this(g(x)). */
Polynomial compose(Polynomial g) {
Polynomial r = zero(field);
for (int i = 0; i < coeff.length; i++) {
r = r.add(g.pow(i).mul(coeff[i]));
}
return r;
}
public boolean equals(Object x) {
return equals((Polynomial) x);
}
public boolean equals(Polynomial x) {
if (coeff.length != x.coeff.length) return false;
for (int i = 0; i < coeff.length; i++) {
if (!coeff[i].equals(x.coeff[i])) return false;
}
return true;
}
public String toString() {
String s = "";
if (coeff.length == 0) return "0";
for (int i = coeff.length - 1; i >= 0; i--) {
if (coeff[i].equals(field.zero)) continue;
if (s.length() > 0) s = s + "+";
if (i > 0) {
if (!coeff[i].equals(field.one)) {
s = s + coeff[i];
}
s = s + "x";
if (i > 1) {
s = s + "^" + i;
}
} else {
s = s + coeff[i];
}
}
return s;
}
public List<Polynomial> factor() {
// wrapper around factor1 to check result.
List<Polynomial> factors = factor1();
Polynomial x = one(field);
for (Polynomial f : factors) {
x = x.mul(f);
}
assert this.equals(x);
return factors;
}
private List<Polynomial> factor1() {
// zero
if (coeff.length == 0) {
List<Polynomial> factors = new ArrayList<Polynomial>();
factors.add(zero(field));
return factors;
}
// constants
if (coeff.length == 1) {
List<Polynomial> factors = new ArrayList<Polynomial>();
factors.add(constant(coeff[0], field));
return factors;
}
// linear terms
if (coeff.length == 2) {
List<Polynomial> factors = new ArrayList<Polynomial>();
if (coeff[1].equals(field.one)) {
factors.add(this);
} else {
factors.add(constant(coeff[1], field));
factors.add(monic());
}
return factors;
}
// call factor2 with a monic polynomial of degree >= 2.
if (lead().equals(field.one)) {
return factor2();
} else {
List<Polynomial> factors = monic().factor2();
factors.add(constant(lead(), field));
return factors;
}
}
// polynomial must have degree >= 2 and be monic
private List<Polynomial> factor2() {
assert degree() >= 2;
assert lead().equals(field.one);
// look for a repeated factor
Polynomial f = gcd(diff());
if (f.degree() > 0) {
Polynomial f1 = f;
Polynomial f2 = div(f)[0];
List<Polynomial> factors = f1.factor();
factors.addAll(f2.factor());
return factors;
}
return factor3();
}
// polynomial must have degree >= 2, be monic, and be square free
private List<Polynomial> factor3() {
assert degree() >= 2;
assert lead().equals(field.one);
assert gcd(diff()).degree() == 0;
// do distinct degree factorization
// http://planetmath.org/encyclopedia/DistinctDegreeFactorization.html
Polynomial p = this;
List<Polynomial> factors = new ArrayList<Polynomial>();
// x^(q^k) - x mod p contains all the degree-k irreducible
// polys where q = |F|.
// xqkx = x^(q^k) - x. We start it off with k == 0 which gives xqkx = 0.
Polynomial xqkx = zero(field);
// try all degrees which might be a factor of p.
// (if p is reducible, it must have a factor of degree <= p.degree()/2)
for (int k = 1; k <= p.degree()/2; k++) {
// compute xqkx from previous value
// - add x
// - raise to the qth power x^(q^k) = (x^(q^(k-1)))^q
// - subtract x
xqkx = xqkx.add(x(field)).modPow(field.size, p).sub(x(field));
// compute gcd with p
Polynomial d = p.gcd(xqkx);
if (d.degree() > 0) {
if (d.degree() == k) { // exactly one factor of degree k
factors.add(d);
} else { // several factors of degree k
assert d.degree() % k == 0 : d.degree() + " " + k;
factors.addAll(d.factor4(k));
}
p = p.div(d)[0];
if (p.degree() == 0) return factors;
assert p.degree() > k;
}
}
// remaining polynomial must be irreducible
factors.add(p);
return factors;
}
// polynomial must have degree >= 2d, be monic, square free, and factor into
// irreducible factors of degree exactly d.
private List<Polynomial> factor4(int d) {
assert degree() >= 2 * d;
assert degree() % d == 0;
assert lead().equals(field.one);
assert gcd(diff()).degree() == 0;
// Cantor-Zassenhaus algorithm
assert field.size != 2; // TODO: handle later?
Random r = new Random(); // TODO: seed
Polynomial p = this;
BigInteger e = BigInteger.valueOf(field.size).pow(d).subtract(BigInteger.ONE).shiftRight(1);
while (true) {
// pick a random t of degree < 2d
FieldElem[] elts = new FieldElem[2*d];
for (int i = 0; i < elts.length; i++) {
elts[i] = field.random(r);
}
Polynomial t = new Polynomial(elts, field);
// compute t^((q^d - 1) / 2) - 1 mod p
t = t.modPow(e, p).sub(one(field));
// hopefully t and p have a factor in common
Polynomial f = p.gcd(t);
if (f.degree() > 0 && f.degree() < p.degree()) { // found a factor of p
Polynomial f1 = f;
Polynomial f2 = p.div(f)[0];
List<Polynomial> factors = new ArrayList<Polynomial>();
if (f1.degree() == d) {
factors.add(f1);
} else {
assert f1.degree() % d == 0;
factors.addAll(f1.factor4(d));
}
if (f2.degree() == d) {
factors.add(f2);
} else {
assert f2.degree() % d == 0;
factors.addAll(f2.factor4(d));
}
return factors;
}
}
}
public static void main(String[] args) {
Field f = new IntModPrimeField(97);
Polynomial a = new Polynomial(new FieldElem[]{f.nth(6), f.nth(7), f.nth(1)}, f);
Polynomial b = new Polynomial(new FieldElem[]{f.nth(91-6), f.nth(91-5), f.nth(1)}, f);
System.out.println(a);
System.out.println(b);
Polynomial c = a.gcd(b);
System.out.println(c);
a = new Polynomial(new FieldElem[]{f.nth(1), f.nth(1)}, f);
b = new Polynomial(new FieldElem[]{f.nth(0), f.nth(1), f.nth(1)}, f);
System.out.println(a);
System.out.println(b);
c = a.gcd(b);
System.out.println(c);
a = new Polynomial(new FieldElem[]{f.nth(1), f.nth(1), f.nth(1), f.nth(1)}, f);
b = new Polynomial(new FieldElem[]{f.nth(0), f.nth(0), f.nth(1)}, f);
System.out.println(a);
System.out.println(b);
c = a.gcd(b);
System.out.println(c);
a = new Polynomial(new FieldElem[]{f.nth(1), f.nth(1), f.nth(1), f.nth(1), f.nth(1)}, f);
b = new Polynomial(new FieldElem[]{f.nth(1), f.nth(0), f.nth(1)}, f);
System.out.println(a);
System.out.println(b);
c = a.gcd(b);
System.out.println(c);
System.out.println(a.diff());
a = new Polynomial(new FieldElem[]{f.nth(1), f.nth(3), f.nth(3), f.nth(1)}, f);
System.out.println(a + ": " + a.factor());
a = new Polynomial(new FieldElem[]{f.nth(2), f.nth(2)}, f);
System.out.println(a + ": " + a.factor());
a = one(f);
System.out.println(a + ": " + a.factor());
a = new Polynomial(new FieldElem[]{f.nth(2)}, f);
System.out.println(a + ": " + a.factor());
a = new Polynomial(new FieldElem[]{f.nth(5), f.zero, f.one}, f);
System.out.println(a + ": " + a.factor());
a = new Polynomial(new FieldElem[]{f.one, f.one}, f);
System.out.println(a + ": " + a.factor());
a = new Polynomial(new FieldElem[]{f.nth(5), f.zero, f.one}, f);
a = a.mul(new Polynomial(new FieldElem[]{f.one, f.one}, f));
System.out.println(a + ": " + a.factor());
// random big polys
final int degree = 10;
final int N = 100;
Random r = new Random(1234);
FieldElem[] elts = new FieldElem[degree];
for (int i = 0; i < N; i++) {
for (int j = 0; j < elts.length; j++) {
elts[j] = f.random(r);
}
a = new Polynomial(elts, f);
System.out.println(a + ": " + a.factor());
}
a = Polynomial.x(f).pow(97).sub(Polynomial.x(f));
System.out.println(a + ": " + a.factor());
// x^2 - 322 factors into (x+7746)(x+155)
f = new IntModPrimeField(7901);
a = new Polynomial(new FieldElem[]{f.nth(7901-322), f.zero, f.one}, f);
System.out.println(a + ": " + a.factor());
// irreducible
a = new Polynomial(new FieldElem[]{f.nth(2), f.zero, f.one}, f);
System.out.println(a + ": " + a.factor());
a = new Polynomial(new FieldElem[]{f.zero, f.one, f.one}, f);
a = a.compose(new Polynomial(new FieldElem[]{f.nth(2), f.one}, f));
System.out.println(a + ": " + a.factor());
}
}
==============================================================
【程序81】BenYuan.java
/**
* <p>Title: 本原多项式生成算法实现。利用此JAVA程序可求得任意阶本原多项式系数</p>
*
* <p>Description: 本程序是本原多项式生成算法实现,结果中1....表示多项式系数(从高到低依次排列)</p>
*
* <p>Copyright: Copyright (c) 2008</p>
*
* <p>Company:建工学院 </p>
* <p>Reference:维普资讯网 文章标号1000-3428(2004)16-0108-02 伪随机序列中本原多项式生成算法 作者:吕辉 何晶 王刚</p>
* @author 04信息程晟
* @version 1.0
*/
import java.util.*;
public class BenYuan {
public static void main(String args[] ) {
System.out.print("本程序功能是判断本原多项式,请输入多项式最高次数:n=");
byte[] temp=new byte[4];
int n;//保存多项式系数
try{
System.in.read(temp);
}catch(Exception ex) {
}
try{
n=Integer.parseInt(new String(temp).trim());
//System.out.println(n);
LinkedList<StringBuffer> array=new LinkedList<StringBuffer>();//存储多项式系数
int length=(int) Math.pow(2, n-1);
//利用2进制与10进制转化保存需要判断的多项式系数
for(int i=0;i<length;i++) {
StringBuffer one=new StringBuffer(Integer.toBinaryString(i));
if(one.length()<n-1) {
StringBuffer rightone=new StringBuffer();
for(int i1=0;i1<n-1-one.length();i1++) {
rightone.append(0);
}
//System.out.println(rightone);
rightone.append(one);
one=new StringBuffer(rightone);
}
int sum=0;//保存系数之和(模2运算)
//偶数项的多项式去除
for(int i2=0;i2<n-1;i2++) {
sum+=(int)one.charAt(i2)-48;
}
if(sum%2==1) {
one.insert(0, "1");
one.insert(one.length(), "1");
array.add(one);
}
//System.out.println(one);
}
System.out.println("生成多项式组合"+array);
//筛选出需要判断的多项式系数(本原多项式的互反多项式也是本原多项式,遇到互反多项式只记一次)
for(int i3=0;i3<array.size();i3++) {
StringBuffer element=new StringBuffer(array.get(i3).toString());
StringBuffer elementReverse=new StringBuffer(element.reverse());
for(int j=i3+1;j<array.size();j++) {
if(elementReverse.toString().equals(array.get(j).toString())) {//注意此地方比较类型要一致String
array.remove(j);break;
}
}
}
System.out.println("参加判断多项式组合"+array);
int count=0;
for(int i4=0;i4<array.size();i4++) {
StringBuffer str=new StringBuffer(array.get(i4).toString().substring(1, n+1));
//System.out.println(str);
StringBuffer leftstr=str;
for(int j1=n+1;j1<Math.pow(2, n);j1++) {
char firstbit=leftstr.charAt(0);
leftstr=new StringBuffer(leftstr.substring(1, str.length()));
leftstr.append(0);
if(firstbit=='1') {
for(int k=0;k<leftstr.length();k++) {
int temp1=(leftstr.charAt(k)-48+str.charAt(k)-48)%2;
//System.out.println(temp1);
leftstr.replace(k, k+1, String.valueOf(temp1));
}
}
if(Long.parseLong(leftstr.toString())==1&&j1<Math.pow(2, n)-1) {
System.out.println(array.get(i4)+"不是本原多项式");break;
}else if(Long.parseLong(leftstr.toString())==1&&j1==Math.pow(2, n)-1) {
System.out.println(array.get(i4)+"是本原多项式");
String strold=new String(array.get(i4).toString());
StringBuffer reverse=new StringBuffer(strold).reverse();
//System.out.println(strold);
//System.out.println(reverse);
if(strold.equals(reverse.toString())) {
count+=1;
}else {
count+=2;
}
break;
//System.out.println(count);
}
}
System.out.println("**********");
}
System.out.println(n+"次多项式所有本原多项式个数为:"+count);
}catch(Exception ex) {
System.out.println(ex.getMessage());
}
}
}
==============================================================
【程序86】
/*
F:\hxh1\MathTool\有限群\Un20140619\Un>javac ord0.java
F:\hxh1\MathTool\有限群\Un20140619\Un>java ord0
ord(_7)2=3
ord(_7)3=6
*/
public class ord0{
public static void main(String[] args) {
int a=2,n=7;
System.out.print("ord(_7)2="+ord(a,n) + "\r\n");
a=3;n=7;
System.out.print("ord(_7)3="+ord(a,n) + "\r\n");
}
static int PowerMod(int a,int x,int n) {
int r = 1;
for(int i=1;i<=x;i++) {
//r=r*(a%n);
r=r*a;
}
//return r;
return r%n;
}
// a模n的次数(阶)
static int ord(int a, int n) {
int r = 0;
for(int i=1;i<=n;i++) {
int ret=PowerMod(a,i,n);
if(ret==1)
return i;
}
return r;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】