Java期末练习(一)

 

                                                                                                                    2019.01.05  考试后纪念下还不错的成绩

  本文为博主的Java期末练习整理。鉴于不明原因,不怎么喜欢Java(可能自己比较独吧),一学期的Java课也没咋听过,这里还是蛮愧疚的。不过在自己写过这些基本练习之后,觉得Java还是蛮不错的。以下练习题来自于PTA,都是些最基本的,尽管Java没咋学,不过有C/C++基础,应该刷起来会比较快。(⊙o⊙)…这里不是想吹自己多牛,能几天速成Java(我也不可能做到),想告诉大家,一定不要排斥新东西、害怕新东西,借口自己没什么兴趣就可以不努力,只有在你做到很好的时候,才会为了捍卫自己的领域而产生源源不断的兴趣。新年加油!!!

                                                                                                                                                    2019.01.01


7-1 Geometry: area of a triangle (10 分)

Write a program that prompts the user to entern three points (x1,y1),(x2,y2), (x3,y3) of a triangle and displays its area. The formula for computing the area of a triangle is s = (side1 + side2 + side3)/2; area = Math.sqrt(s (s - side1) (s - side2) (s - side3));

input style :

Enter three points for a triangle,there is a space among the values. i.e : 1.5 -3.4 4.6 5 9.5 -3.4

output style:

Output the area. Keep the two decimal places. i.e : The area of the triangle is 33.60.

input sample:

1.5  -3.4  4.6  5  9.5  -3.4

output sample:

The area of the triangle is 33.60.
import java.text.DecimalFormat;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		double x1 = sc.nextDouble();
		double y1 = sc.nextDouble();
		double x2 = sc.nextDouble();
		double y2 = sc.nextDouble();
		double x3 = sc.nextDouble();
		double y3 = sc.nextDouble();
		
		double side1 = Math.sqrt((x1-x3)*(x1-x3)+(y1-y3)*(y1-y3));
		double side2 = Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
		double side3 = Math.sqrt((x2-x3)*(x2-x3)+(y2-y3)*(y2-y3));
		double s = (side1+side2+side3)/2;
		double area = Math.sqrt(s*(s - side1)*(s - side2)*(s - side3));
		
        DecimalFormat df = new DecimalFormat("#.00");
        System.out.println("The area of the triangle is "+df.format(area)+".");
		
		sc.close();
	}
}

7-2 Science: day of the week (10 分)

Zellers congruence is an algorithm developed by Christian Zeller to calculate the day of the week. The formula is int h =(int) (q+ 26 (m + 1) / 10 + k + k / 4 + j / 4 + 5 j) % 7;

  • where h is the day of the week (0: Saturday, 1: Sunday, 2: Monday, 3: Tuesday, 4:
  • Wednesday, 5: Thursday, 6: Friday).
  • q is the day of the month.
  • m is the month (3: March, 4: April, 12: December). January and February, are counted as months 13 and 14 of the previous year.
  • j is the century (i.e. year/100)
  • k is the year of the century (i.e., year% 100).
  • Write a program that prompts the user to enter a year, month, and day of the month, and displays the name of the day of the week.

input style :

Enter three value for a date,there is a space among the year , month and the day. i.e : 2002 3 26

output style:

Output the day of the week. i.e : Tuesday

input sample:

2002 3 26

output sample:

Tuesday
import java.text.DecimalFormat;
import java.util.Scanner;
class day_of_the_week {
    int year, month, day;
    int q, m, j, k, h;

    day_of_the_week(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }

    void init() {
        q = day;
        if (month < 3) {
            m = 12 + month;
            year -= 1;
        } else
            m = month;
        j = year / 100;
        k = year % 100;
    }

    void result() {
        init();
        int h = (q + 26 * (m + 1) / 10 + k + k / 4 + j / 4 + 5 * j) % 7;
        switch (h) {
            case 0:
                System.out.println("Saturday");
                break;
            case 1:
                System.out.println("Sunday");
                break;
            case 2:
                System.out.println("Monday");
                break;
            case 3:
                System.out.println("Tuesday");
                break;
            case 4:
                System.out.println("Wednesday");
                break;
            case 5:
                System.out.println("Thursday");
                break;
            case 6:
                System.out.println("Friday");
                break;
            default:
                break;
        }
    }
}

public class Main {
    public static void main(String[] args) {
      Scanner Input = new Scanner(System.in);
        int x1 = Input.nextInt();
        int x2 = Input.nextInt();
        int x3 = Input.nextInt();
        day_of_the_week obj = new day_of_the_week(x1, x2, x3);
        obj.result();
    }
}

7-3 wind-chill temperature (10 分)

(Science: wind-chill temperature) How cold is it outside? The temperature alone is not enough to provide the answer. Other factors including wind speed, relative humidity, and sunshine play important roles in determining coldness outside. In 2001, the National Weather Service (NWS) implemented the new wind-chill temperature to measure the coldness using temperature and wind speed. The formula is given as follows: windCold = 35.74 + 0.6215 x fahrenheit - 35.75 x Math.pow(speed, 0.16) + 0.4275 x fahrenheit x Math.pow(speed, 0.16);

input style :

Enter three value for the Fahrenheit and wind speed miles per hour.

output style:

Output the wind chill index.

input sample:

5.3
6

output sample:

The wind chill index is -5.56707
import java.util.Scanner;
import java.lang.Math;
//import java.text.DecimalFormat;

public class Main 
{
    public static void main(String[] args) 
    {
       // DecimalFormat decimalFormat = new DecimalFormat("#.00000");
        Scanner Input = new Scanner(System.in);
        double fahrenheit = Input.nextDouble();
        double speed = Input.nextDouble();
        double WindCold = 35.74 + 0.6215 * fahrenheit - 35.75 * Math.pow(speed, 0.16) + 0.4275 * fahrenheit * Math.pow(speed, 0.16);
        System.out.println("The wind chill index is " + WindCold);
        //System.out.println("The wind chill index is " + decimalFormat.format(WindCold));
        Input.close();
    }
}

7-4 check ISBN-10 (10 分)

(Business: check ISBN-10) An ISBN-10 (International Standard Book Number) consists of 10 digits: d1d2d3d4d5d6d7d8d9d10. The last digit, d10, is a checksum, which is calculated from the other nine digits using the following formula: (d1 x 1 + d2 x 2 + d3 x3 + d4 x 4 + d5 x5 + d6 x 6 + d7 x 7+ d8 x 8 + d9 x 9 ) % 11 If the checksum is 10, the last digit is denoted as X according to the ISBN-10 convention. Write a program that prompts the user to enter the first 9 digits and displays the 10-digit ISBN (including leading zeros). Your program should read the input as an integer.

input style :

Enter the first 9 digits

output style:

Displays the 10-digit ISBN.

input sample:

123456789

output sample:

The ISBN-10 number is 123456789X
import java.util.Scanner;

public class Main 
{
    public static void main(String[] args) 
    {
        Scanner Input = new Scanner(System.in);
        String str = Input.next();
        char[] ch = str.toCharArray();
        int d[] = new int[15];
        for(int i=0; i<9; i++)
        	d[i+1] = ch[i];
        d[10] = ((d[1]-'0')*1 + (d[2]-'0')*2 + (d[3]-'0')*3 + (d[4]-'0')*4 + (d[5]-'0')*5
        		+(d[6]-'0')*6 + (d[7]-'0')*7 + (d[8]-'0')*8 + (d[9]-'0')*9) % 11;
        if(d[10]==10)
        	System.out.println("The ISBN-10 number is " + str + "X");
        else
        	System.out.println("The ISBN-10 number is " + str + d[10] );
        Input.close();
    }
}

7-5 Palindrome integer (10 分)

(Palindrome integer) Write the following two methods
//Return the reversal of an integer, i.e. reverse(456) returns 654 public static int reverse(int number) Return true if number is palindrome public static boolean isPalindrome(int number) Use the reverse method to implement isPalindrome. A number is a palindrome if its reversal is the same as itself. Write a test program that prompts theuser to enter an integer and reports whether the integer is a palindrome.

input style :

Enter one int number.

output style:

Displays whether the integer is a palindrome.

input sample:

1214344232

output sample 1:

1214344232 is NOT a palindrome.

input sample 2:

123454321

output sample:

123454321 is a palindrome.
import java.util.Scanner;

public class Main 
{
    public static void main(String[] args) 
    {
        Scanner Input = new Scanner(System.in);
        String str = Input.next();
        char[] ch_str = str.toCharArray();
        char[] ch_str2 = new char[100];
        boolean flag=false;
        for(int i=str.length()-1,j=0; i>=0; j++,i--)
        	ch_str2[j] = ch_str[i];
        for(int i=0; i<str.length(); i++)
        	if(ch_str[i]!=ch_str2[i])
        		flag = true;
        if( flag!=false )
        	System.out.print(str+" is NOT a palindrome.");
        else
        	System.out.print(str+" is a palindrome.");
        Input.close();
    }
}

7-6 Count the letters in a string (10 分)

(Count the letters in a string) Write a method that counts the number of letters in a string using the following header: public static int countLetters(String s) 
Write a test program that prompts the user to enter a string and displays the number of letters in the string.

input style :

Enter a string

output style:

Displays the number of the letters in the string.

input sample:

qwe&&&,,;#@23qer

output sample:

The number of letters inside the string is: 6
import java.util.Scanner;

public class Main 
{
    public static void main(String[] args) 
    {
        Scanner Input = new Scanner(System.in);
        String str = Input.nextLine();
        char[] ch_str = str.toCharArray();
        int count=0;
        for(int i=0; i<str.length(); i++)
        	if( (ch_str[i]>='a' && ch_str[i] <= 'z') || (ch_str[i]>='A' && ch_str[i] <= 'Z'))
        		count++;
        System.out.print("The number of letters inside the string is: "+count);
        	
        Input.close();
    }
}

7-7 Convert milliseconds to hours, minutes, and seconds (10 分)

(Convert milliseconds to hours, minutes, and seconds) Write a method that converts milliseconds to hours, minutes, and seconds using the following header: public static String convertMillis(long millis) The method returns a string as hours:minutes:seconds. For example, convertMillis(5500) returns a string 0:0:5, convertMillis(100000) returns a string 0:1:40, and convertMillis(555550000) returns a string 154:19:10

input style :

Enter a long

output style:

Displays the time with the format xx:xx:xx.

input sample:

5500

output sample:

0:0:5
import java.util.Scanner;

public class Main 
{
    public static void main(String[] args) 
    {
        Scanner Input = new Scanner(System.in);
        long ms = Input.nextLong();
        long hou=0,min=0,sec=0;
        sec = ms/1000;
        if(sec >= 60)
        {
        	min = sec/60;
        	sec = sec%60;
        }
        if(min >= 60)
        {
        	hou = min/60;
        	min = min%60;
        }	
        System.out.print(hou+":"+min+":"+sec);
        	
        Input.close();
    }
}

7-8 Palindromic prime (10 分)

(Palindromic prime) A palindromic prime is a prime number and also palindromic.For example, 131 is a prime and also a palindromic prime, as are 313 and 757. Write a program that displays the first 100 palindromic prime numbers. Display 10 numbers per line, separated by exactly one space, as follows: 2 3 5 7 11 101 131 151 181 191 313 353 373 383 727 757 787 797 919 929 ………

input style :

No input.

output style:

Displays first 100 palindromic prime numbers.

input sample:


output sample:

2 3 5 7 11 101 131 151 181 191 
313 353 373 383 727 757 787 797 919 929
………….. (You should complete the other 80 numbers)
//import java.util.Scanner;

public class Main 
{
	static boolean IsPrime(int i)
	{
		boolean flag=true;
		for(int j=2; j<=Math.sqrt(i); j++)
    	{
    		if(i%j==0)
    		{
    			flag=false;
    			break;
    		}	
    	}
    	if(flag==true)
    		return true;
    	else
    		return false;
	}
	static boolean IsHuiWen( int i )
	{
		if( i<=9 )
			return true;
		else if( i<=99 )
		{
			int NewGe = i/10;
			int NewShi = i%10;
			if( NewGe+NewShi*10==i )
				return true;
			else
				return false;
		}
		else if(i<=999)
		{
			int NewGe = i/100;
			int NewShi = i/10%10;
			int NewBai = i%10;
			if( NewGe+NewShi*10+NewBai*100==i )
				return true;
			else
				return false;
		}
		else if(i<=9999)
		{
			int NewGe = i/1000;
			int NewShi = i/100%10;
			int NewBai = i/10%10;
			int NewQian = i%10;
			if( NewGe+NewShi*10+NewBai*100+NewQian*1000==i )
				return true;
			else
				return false;
		}
		else if(i<=99999)
		{
			int NewGe = i/10000;
			int NewShi = i/1000%10;
			int NewBai = i/100%10;
			int NewQian = i/10%10;
			int NewWan = i%10;
			if( NewGe+NewShi*10+NewBai*100+NewQian*1000+NewWan*10000==i )
				return true;
			else
				return false;
		}	
		else //if(i<=999999)
		{
			int NewGe = i/100000;
			int NewShi = i/10000%10;
			int NewBai = i/1000%10;
			int NewQian = i/100%10;
			int NewWan = i/10%10;
			int NewShiWan = i%10;
			if( NewGe+NewShi*10+NewBai*100+NewQian*1000+NewWan*10000+NewShiWan*100000==i )
				return true;
			else
				return false;
		}	
	}
    public static void main(String[] args) 
    {
        //Scanner Input = new Scanner(System.in);
        int count=0;
        for(int i=2; count<100; i++)
        {
        	if(IsPrime(i) && IsHuiWen(i))
        	{
        		System.out.print(i+" ");
        		count++;
        		if(count%10==0)
            		System.out.println();
        	}
        	
        }
    }
}

7-2 The Location class (10 分)

(The Location class) Design a class named Location for locating a maximal value and its location in a two-dimensional array. The class contains public data fields row, column, and maxValue that store the maximal value and its indices in a two-dimensional array with row and column as int types and maxValue as a double type. Write the following method that returns the location of the largest element in a two-dimensional array: public static Location locateLargest(double[][] a) The return value is an instance of Location.Write a test program that prompts the user to enter a two-dimensional array and displays the location of the largest element in the array.

input style :

Enter the row and column and the number in the array. For example: 2 3 234 223 444 111 343 454

output style:

displays the location of the largest element in the array. Such as : e location of the largest element is 454.0 at (1, 2)

input sample:

2 3
234 223 444
111 343 454

output sample:

The location of the largest element is 454.0 at (1, 2)
import java.util.*;

class Location{
	public int row = 0;
	public int column = 0;
	public double maxValue = 0;
	Location(){}
}
public class Main {

	public static Location locateLargest(double [] [] a) {
		Location b = new Location();
		for(int i=0;i<a.length;i++)
			for(int j=0;j<a[i].length;j++)
			{
				if(b.maxValue<a[i][j])
				{
					b.maxValue = a[i][j];
					b.row = i;
					b.column = j;
				}
			}
		return b;
	}
	public static void main(String[] args) {
		Location q = new Location();
		Scanner in = new Scanner(System.in);
		int w = in.nextInt();
		int e = in.nextInt();
		double[][] a = new double[w][e];
		for(int i=0;i<a.length;i++)
			for(int j=0;j<a[i].length;j++)
			{
				a[i][j] = in.nextDouble();
			}
		q = locateLargest(a);
		//System.out.printf("The location of the largest element is %.1f at (%d, %d)\n",q.maxValue,q.row,q.column);
		System.out.println("The location of the largest element is "+q.maxValue+" at ("+q.row+", "+q.column+")");
		in.close();
		
		
	}

}

7-3 Square numbers (10 分)

(Square numbers)Find the first ten square numbers that are greater than Long.MAX_VALUE. A square number is a number in the form of n2. For example, 4, 9, and 16 are square numbers. Find an efficient approach to run your program fast.

input style :

No input.

output style:

Displays the first ten square numbers that are greater than Long.MAX_VALUE.

input sample:


output sample:

9223372037000250000
(Your program should show the other nine squared numbers.Every squared number will show in next line)
import java.math.*;

public class Main {
    public static void main(String[] args) {
    	Long maxValue=Long.MAX_VALUE;
        BigInteger a= new BigInteger("3037000500");
        BigInteger max =new BigInteger(maxValue.toString());
        int n=0;
        while (n<10){
        	
            if( a.multiply(a).compareTo(max)>0){
                System.out.println(a.multiply(a));
                n++;
            }
            a=a.add(BigInteger.ONE);
        }
    }
}

7-4 Largest rows and columns (10 分)

(Largest rows and columns) Write a program that input fills in 0s and 1s into an n-by-n matrix, prints the matrix, and finds the rows and columns with the most 1s. (Hint: Use two ArrayLists to store the row and column indices with the most 1s.) Here is a sample run of the program: Enter the array size n: 4 The random array is 0 0 1 1 0 0 1 1 1 1 0 1 1 0 1 0 The largest row index: 2 The largest column index: 2, 3

input style :

Enter the array size n and the n x n numbers that input 0s and 1s . The first line input the length n of the matrix . And input the value of the matrix the other n line.

output style:

Displays the rows and columns with the most 1s..

input sample:

4
0 0 1 1
0 0 1 1
1 1 0 1
1 0 1 0

output sample:

Highest row: [2]
Highest column: [2, 3]
import java.math.*;
import java.util.*;

public class Main
{
	public static void main(String[] args)
	{
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		int[][] a = new int[n][n];
		int[] row = new int[n];
		int[] column = new int[n];
		int max_row = 0;
		int max_column = 0;
		// for (int i=0;i<n;i++)
		// row[i] = 0;
		for (int i = 0; i < n; i++)
		{	
			for (int j = 0; j < n; j++)
			{
				a[i][j] = in.nextInt();
				if (a[i][j] == 1)
					row[i]++;
			}
			if (row[i] > max_row)
				max_row = row[i];
		}
		for (int i = 0; i < n; i++)
		{
			for (int j = 0; j < n; j++)
			{
				if (a[j][i] == 1)
					column[i]++;
			}
			if (column[i] > max_column)
				max_column = column[i];
		}
		int b = 0;
		System.out.print("Highest row: [");
		for(int i=0;i<n;i++)
		{
			
			if(row[i]==max_row)
			{
				if((++b) == 1)
					System.out.print(i);
				else System.out.print(" ,"+i);
				
			}
		}
		b = 0;
		System.out.println("]");
		System.out.print("Highest column: [");
		for(int i=0;i<n;i++)
		{
			if(column[i]==max_column)
				if((++b) == 1)
					System.out.print(i);
				else System.out.print(", "+i);
		}
		System.out.println("]");
	}
}

7-5 Remove duplicates (10 分)

(Remove duplicates) Write a method that removes the duplicate elements from an array list of integers using the following header: public static void removeDuplicate(ArrayList list) Write a test program that prompts the user to enter n integers to a list ,After sort the distinct intergers and displays the distinct integers separated by exactly one space.

input style :

Input the number n for the length of the array in the first line, and the next line input n integers for the array..

output style:

Displays the distinct integers separated by exactly one space

input sample:

5
32 43 32 22 22

output sample:

32 43 22
import java.util.*;
public class Main{
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		int num = s.nextInt();
		int []a = new int[num];
		int []b = new int[num];
		int flag = 1;
		int count = 0;
		int index=0;
		for(int i=0;i<num;i++){
			flag = 1;
			int temp = s.nextInt();
			index++;
			for(int j=0;j<index;j++){
				if(temp==a[j]){
					flag = 0;
					break;
				}
			}
			if(flag==1){
				a[i]=temp;
				b[count]=temp;
				count++;
				
			}else{
				continue;
			}
		}
		for(int m=0;m<count;m++){
			System.out.print(b[m]+" ");
		}
		
		
		// System.out.print(b[count-1]);
		// System.out.println();
	}
}

7-6 Combine two lists then sorted it (10 分)

 (Combine two lists then sorted it.)
   Write a method that returns the union of two array lists of integers using the following header:
   public static ArrayList<Integer> union( ArrayList<Integer> list1, ArrayList<Integer> list2)
  For example, the union of two array lists {2,3,1,5} and {3,4,6} is {2, 3, 1, 5, 3, 4, 6}.
  Write a test program that prompts the user to enter two lists, then sorted the union list, finally displays their sorted union. The numbers are separated by exactly one space in the output.
 Write a test program that prompts the user to enter the two number m,n  for the length of two arrays in the first line, and the next two line input m integer and n intergers for the two array. After sort theunion intergers and displays the sorted union list separated by exactly one space.  

input style :

Input the two number m,n for the length of two arrays in the first line, and the next two line input m integer and n intergers .

output style:

Displays the sorted union list separated by exactly one space..

input sample:

3 4
23 44 32
12 43 32 44

output sample:

12 23 32 32 43 44 44 
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		Scanner in = new Scanner(System.in);
		int n = in.nextInt()+in.nextInt();
		int[] a = new int[n];
		for(int i=0;i<n;i++)
		{
			a[i] = in.nextInt();
		}
		Arrays.sort(a);
		for(int i=0;i<n;i++)
		{
			System.out.print(a[i]+" ");
		}
		
	}

}

7-7 finds the occurrences of a specified character in the string (10 分)

Write a method that finds the number of occurrences of a specified character in the string using the following header: public static int count(String str, char a) For example, count("Welcome", 'e') returns 2. Write a test program that prompts the user to enter a string followed by a character and displays the number of occurrences of the character in the string.

输入格式:

please input the string and the character.

输出格式:

Then output the the number of occurrences of a specified character in the string.

输入样例:

Welcome e

输出样例:

The number of occurrences is 2.

import java.util.Scanner;

public class Main {
	static public void main(String []args)
	{
		Scanner scan = new Scanner(System.in);	//System.in.read(a);
		String a = scan.next();
		String b = scan.next();
		char[] c=a.toCharArray();
		char[] d =b.toCharArray();
		int count=0;
		for(int i=0;i<a.length();i++)
		{
			if(c[i]==d[0])
			{
				count++;
			}
		}
		System.out.print("The number of occurrences is "+count+".");
		scan.close();
	}
}

7-8 求解给定字符串的前缀 (10 分)

求解给定字符串的前缀。

输入格式:

输入数目不定的多对字符串,每行两个,以空格分开。 例如: filename filepath Tom Jack

输出格式:

返回两个字符串的最大前缀,例如: The common prefix is file No common prefix

输入样例:

filename filepath
Tom Jack

输出样例:

The common prefix is file
No common prefix
import java.util.Scanner;
public class Main 
{
    public static void main(String[] args)  
    {  
    	Scanner input = new Scanner(System.in);
    	while(true)
    	{
    		
    		String str1 = input.next();
        	String str2 = input.next();
        	StringBuffer Buffer_str1 = new StringBuffer(str1);
        	StringBuffer Buffer_str2 = new StringBuffer(str2);
        	
        	CharSequence result = "1";
        	for(int i=1,j=1; i<Buffer_str1.length()&&j<Buffer_str2.length(); i++,j++)
        		if (  Buffer_str1.subSequence(0, i).equals(Buffer_str2.subSequence(0, j)) )
        			result = Buffer_str1.subSequence(0, j);
        	if( result.equals("1") )
        		System.out.println("No common prefix");
        	else
        		System.out.println("The common prefix is " + result);
    	}    	
    }
}

 7-9 求解给定两个字符串的后缀 (10 分)

给定两个字符串,求解给定字符串的后缀。按照如下的格式进行输出

输入格式:

输入为一对字符串,以空格分开。 例如:

father mather 

输出格式:

返回两个字符串的最大后缀,例如:

The common suffix is ather. 

又如:

输入样例:

Tom Jack

输出样例:

No common suffix.
import java.util.Scanner;
public class Main 
{
    public static void main(String[] args)  
    {  
    	Scanner input = new Scanner(System.in);
    	
    	String str1 = input.next();
    	String str2 = input.next();

    	StringBuffer Buffer_str1 = new StringBuffer(str1);
    	StringBuffer Buffer_str2 = new StringBuffer(str2);
    	
    	CharSequence result = "1";
    	for(int i=str1.length()-1,j=str2.length()-1; i>=0&&j>=0; i--,j--)
    		if (  Buffer_str1.subSequence(i, str1.length()).equals(Buffer_str2.subSequence(j, str2.length())) )
    			result = Buffer_str1.subSequence(i, str1.length());
    	if( result.equals("1") )
    		System.out.print("No common suffix.");
    	else
    		System.out.print("The common suffix is " + result + ".");
        input.close();
    }
}

 


7-10 求阶乘factorial (10 分)

编程从键盘输入一个整数,计算出阶乘并输出。

输入格式:

输入 39

输出格式:

输出:20397882081197443358640281739902897356800000000

输入样例:

58

输出样例:

2350561331282878571829474910515074683828862318181142924420699914240000000000000
import java.util.Scanner;
import java.math.BigInteger;
public class Main 
{
	public static BigInteger compute(BigInteger number)  
    {  
		BigInteger result=new BigInteger("1");
		BigInteger one=new BigInteger("1");
        for(BigInteger i=number; i.intValue()>0; i=i.subtract(one)) 
            result = result.multiply(i);  
        return result;  
    }  

    public static void main(String[] args)  
    {  
    	Scanner input = new Scanner(System.in);
    	BigInteger val=input.nextBigInteger();
        System.out.println(compute(val)); 
        input.close();
    }  
}

 

  • 9
    点赞
  • 46
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值