蓝桥杯 加油 (ง •_•)ง
标题:复数幂
设i为虚数单位。对于任意正整数n,(2+3i)^n 的实部和虚部都是整数。
求 (2+3i)^123456 等于多少? 即(2+3i)的123456次幂,这个数字很大,要求精确表示。
答案写成 “实部±虚部i” 的形式,实部和虚部都是整数(不能用科学计数法表示),中间任何地方都不加空格,实部为正时前面不加正号。(2+3i)^2 写成: -5+12i,
(2+3i)^5 的写成: 122-597i
注意:需要提交的是一个很庞大的复数,不要填写任何多余内容。
package JB第09届省赛;
import java.io.*;
//import java.io.FileOutputStream;
//import java.io.PrintStream;
import java.math.BigInteger;
public class A03_复数幂2 {
public static void main(String[] args) {
try {
//改变输出流,输出到work.txt文件
PrintStream ps = new PrintStream(new FileOutputStream("G:\\work.txt"));
System.setOut(ps); //文件输出 用System.out.println()即可将内容输出到文件中
BigInteger a = new BigInteger("2");
BigInteger b = new BigInteger("3");
BigInteger x = new BigInteger("2");
BigInteger y = new BigInteger("3");
for(int i = 0; i < 123455; i++) {
BigInteger t = x;
x = x.multiply(a).subtract(y.multiply(b));
y = t.multiply(b).add(y.multiply(a));
}
System.out.println(x + "" + ((y.compareTo(BigInteger.ZERO) > 0)? "+" : "") + y + "i");
} catch (Exception e) { //抛出异常
e.printStackTrace();
}
}
}
- 条件运算符 : (b > 0) ? “+” : “”
- 2次幂: 循环一次 ; 23456次幂: 123455
- 每一次累乘,x与y的值 都要更新(需要临时值t, 保留上一次循环的x值)。
BigInteger t = x; //保留上一次循环的x值 ----- 给y用
x = xa - yb;
y = tb + ya;- 验证算法正确性:
(2+3i)^2:-5+12i
(2+3i)^3:-46+9i
(2+3i)^4:-119-120i
(2+3i)^5:122-597i
(2+3i)^6:2035-828i- 运行上面的程序,在控制台看不到任何输出—标准输出不再输出到屏幕,
而是输出到了相应的文件中。- System类里提供了如下三个重定向标准输入/输出的方法:
1、static void setErr(PrintStream err) : 重定向“标准”错误输出流
2、static void setIn(InputStream in) : 重定向“标准”输入流
3、static void setOut(PrintStream out) : 重定向“标准”输出流- (1)程序有时需要处理大整数,java.math.BigInteger提供任意精度的整数运算:
(2)BigInteger类的常用方法:
加法:public BigInteger add(BigInteger val)
减法:public BigInteger subtract(BigInteger val)
乘法:public BigInteger multiply(BigInteger val)
除法:public BigInteger devide(BigInteger val)
取余:public BigInteger remainder(BigInteger val)
比较:public int compareTo(BigInteger val) 返回比较结果(1、-1、0)
- 错误解法示例:
- 代码运行截图1:
- 代码运行截图2:
- 将 核心代码 放入 try{}代码块 中,运行效果 与 上图 一致:
Java PrintStream 示例 :
package JB第09届省赛;
import java.io.FileOutputStream;
import java.io.PrintStream;
public class A03_PrintStream { // Redirectout
public static void main(String[] args) {
try {
//一次性创建PrintStream输出流
PrintStream ps = new PrintStream(new FileOutputStream("G:\\a.txt"));
{
//将标准输出重定向到ps输出流
System.setOut(ps);
//向标准输出输出一个字符串
System.out.println("普通字符串");
//向标准输出输出一个对象
System.out.println(new A03_PrintStream());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
- Java PrintStream 示例 ----- 程序运行截图1:
- Java PrintStream 示例 ----- 程序运行截图2:
参考 BLOG:
- https://blog.csdn.net/yinxiaobao97/article/details/79929549
- https://blog.csdn.net/weixin_40857816/article/details/78396918
客官,点个赞再走啊,谢谢您嘞~