JAVA实验报告处理大整数.doc_第1页
JAVA实验报告处理大整数.doc_第2页
JAVA实验报告处理大整数.doc_第3页
全文预览已结束

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

实验4 处理大整数1. 相关知识点程序有时需要处理大整数,java.math包中的BigInteger类提供任意精度的整数运算。可以使用构造方法:public BigInteger(Sring val)构造一个十进制的BigInteger对象。该构造方法可以发生NumberFormatException异常,也就是说,字符串参数val中如果含有非数字字母就会发生NumberFormatException异常。2. 实验目的本实验的目的是让学生掌握BigInteger类的常用方法。3. 实验要求编写一个java应用程序,计算2个大整数的和、差、积、商,并计算出一个大整数的因子个数(因子中不包括1和大整数本身)。4. 程序模板/HandBigIntegerExample.javaimport java.math.*;class BigIntegerExamplepublic static void main(String args)BigInteger n1 = new BigInteger(987654321987654321987654321),n2 = new BigInteger(123456789123456789123456789),result = null;result = n1.add(n2);System.out.println(和: + result.toString();result = n1.subtract(n2);System.out.println(差: + result.toString();result = n1.multiply(n2);System.out.println(积: + result.toString();result = n1.divide(n2);System.out.println(商: + result.toString();BigInteger m = new BigInteger(17637),COUNT = new BigInteger(0),ONE = new BigInteger(1),TWO = new BigInteger(2);System.out.println(m.toString() + 的因子有:);for (BigInteger i = TWO;pareTo(m) 0;i = i.add(ONE)if(m.remainder(i).compareTo(BigInteger.ZERO)=0)COUNT = COUNT.add(ONE);System.out.print( + i.toString();System.out.println();System.out.println(m.toString() + 一共有 + COUNT.toString() + 个因子);5. 运行效果示例程序运行结果如图所示:6. 实验指导只要计算机的内存足够大,就可以处理任意大的整数。BigInteger类的toString()方法返回当前大整数对象十进制的字符串表示。7. 实验后练习(1) 编写程序,计算大整数的阶乘。/HandBigIntegerExample1.javaimport java.math.*;class BigIntegerExample1public static void main(String args)BigInteger n1 = new BigInteger(50);BigInteger n2 = new BigInteger(1);BigInteger one = new BigInteger(1);for(BigInteger i=one;pareTo(n1) =0;i = i.add(one)n2=n2.multiply(i);System.out.println(n1.toString() + 的阶乘为: + n2.toString();运行结果如下:(2) 编写程序,计算1+2+3.的前99999999项的和。/HandBigIntegerExample2.javaimport java.math.*;class BigIntegerExample2public static void main(String args)BigInteger n1 = new BigInteger(99999999);BigInteger n2 = new BigInteger(0);BigInteger one = new BigInteger(1);for(BigInteger i=one;pareTo(

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论