"Java Classic algorithm 40 questions (top)"

Source: Internet
Author: User
Tags gcd greatest common divisor repetition

"Program 1"? Title: Classical Questions: There are a pair of rabbits, from the 3rd month after birth a pair of rabbits each month, the small rabbit to the fourth month after the birth of a pair of rabbits each month, if the rabbit is not dead, ask each month the total number of rabbits?
1. Program Analysis:? The law of the Rabbit for the series 1,1,2,3,5,8,13,21 .... ?
public class exp2{
public static void Main (String args[]) {
int i=0;
for (i=1;i<=20;i++)
System.out.println (f (i));
}
public static int f (int x)
{
if (x==1 | | x==2)
return 1;
Else
return f (x-1) +f (x-2);
}
}
Or
public class exp2{
public static void Main (String args[]) {
int i=0;
Math MyMath = new Math ();
for (i=1;i<=20;i++)
System.out.println (MYMATH.F (i));
}

}
Class Math
{
public int f (int x)
{
if (x==1 | | x==2)
return 1;
Else
return f (x-1) +f (x-2);
}
}

"Program 2"? Title: Determine how many primes between 101-200 and the output of all primes.
1. Program Analysis: The method of judging primes: to remove 2 to sqrt (this number) by a number, if it can be divided evenly,? The
indicates that the number is not a prime and vice versa.
public class exp2{
public static void Main (String args[]) {
int i=0;
Math MyMath = new Math ();
for (i=2;i<=200;i++)
if (Mymath.iszhishu (i) ==true)
System.out.println (i);
}
}
Class math
{
Public boolean Iszhishu (Int. x)
{
for (int i=2;i<=x/2;i++)
if (x% 2==0)
return false;
return true;
}
}

"Program 3"? Title: Print out all the "daffodils", the so-called "Narcissus number" refers to a three-digit number, its number of cubes and equal to the number itself. For example: 153 is a "narcissus number", because the 153=1 three times the square +5 of three +3 Times Square.
1. Program Analysis: Use for loop control 100-999 number, each number decomposition out of bits, 10 bits, hundred.
public class exp2{
public static void Main (String args[]) {
int i=0;
Math MyMath = new Math ();
for (i=100;i<=999;i++)
if (Mymath.shuixianhua (i) ==true)
System.out.println (i);
}
}
Class Math
{
public boolean Shuixianhua (int x)
{
int i=0,j=0,k=0;
i=x/100;
j= (x% 100)/10;
K=x% 10;
if (x==iii+jJj+kKk)
return true;
Else
return false;

}

}
"Program 4"? Title: Decompose a positive integer into factorization. Example: Enter 90, print out 90=2335.?
Program Analysis: The decomposition of n factorization, should first find a minimum prime number k, and then the following steps to complete:?
(1) If the prime number is exactly equal to N, then the process of decomposing the factorization is over and printing can be done.
(2) if n <> K, but n can be divisible by K, then the value of K should be printed, and n divided by the quotient of K, as a new positive integer you, repeat the first step.
(3) If n cannot be divisible by K, the first step is repeated with k+1 as the value of K.
public class exp2{
Public Exp2 () {}
public void Fengjie (int n) {
for (int i=2;i<=n/2;i++) {
if (n%i==0) {
System.out.print (i+ "
");
Fengjie (n/i);
}
}
System.out.print (n);
System.exit (0);////I can't say this, or it will be wrong.
}
public static void Main (string[] args) {
String str= "";
EXP2 c=new exp2 ();
Str=javax.swing.joptionpane.showinputdialog ("Please enter the value of N (Enter exit exit):");
int N;
n=0;
try{
N=integer.parseint (str);
}catch (NumberFormatException e) {
E.printstacktrace ();
}
System.out.print (n+ "decomposition factorization:" +n+ "=");
C.fengjie (N);
}
}
"Program 5"? Title: Use the nesting of conditional operators to complete this topic: Academic scores > = 90 points of the students with a, 60-89 points between the use of B, 60 points below the C expression.
1. Program Analysis: (a> b)? A:b This is a basic example of a conditional operator.
Import javax.swing.;
public class Ex5 {
public static void Main (string[] args) {
String str= "";
Str=joptionpane.showinputdialog ("Please enter the value of N (Enter exit exit):");
int N;
n=0;
try{
N=integer.parseint (str);
}
catch (NumberFormatException e) {
E.printstacktrace ();
}
Str= (n>90? ") A ":(n>60?" B ":" C "));
System.out.println (str);
}
}
"Program 6"? Title: Enter two positive integers m and N to find their greatest common divisor and least common multiple.
1. Program Analysis: Using rolling division.
Greatest common divisor
public class commondivisor{
public static void Main (String args[])
{
Commondivisor (24,32);
}
static int commondivisor (int M, int N)
{
if (n<0| | M&LT;0)
{
System.out.println ("error!");
return-1;
}
if (n==0)
{
System.out.println ("The biggest common divisor is:" +m);
return M;
}
Return Commondivisor (n,m%n);
}
}
Least common multiple and greatest common divisor:
Import Java.util.Scanner;
public class CANDC
{
The following method is to find out greatest common divisor
public static int gcd (int m, int n)
{
while (true)
{
if ((m = m% n) = = 0)
return n;
if ((n = n% m) = = 0)
return m;
}
}
public static void Main (String args[]) throws Exception
{
Get input value
Scanner chin = new Scanner (system.in);
int a = Chin.nextint (), B = chin.nextint ();
int a=23; int b=32;
int c = GCD (A, b);
SYSTEM.OUT.PRINTLN ("Least common multiple:" + A
B/C + "\ n Greatest Common divisor:" + C);
}
}
"Program 7"? Title: Enter a line of characters, respectively, the number of English letters, spaces, numbers and other characters.
1. Program Analysis: Using the while statement, the condition for the input character is not ' \ n '. ?
Import Java.util.Scanner;
public class Ex7 {
public static void Main (String args[])
{
System.out.println ("Please enter string:");
Scanner scan=new Scanner (system.in);
String Str=scan.next ();
String e1= "[\u4e00-\u9fa5]";
String e2= "[A-za-z]";
int counth=0;
int counte=0;
Char[] Arrchar=str.tochararray ();
String[] Arrstr=new string[arrchar.length];
for (int i=0;i<arrchar.length; i++)
{
Arrstr[i]=string.valueof (Arrchar[i]);
}
for (String i:arrstr)
{
if (I.matches (E1))
{
counth++;
}
if (I.matches (E2))
{
counte++;
}
}
System.out.println ("Number of Chinese characters" +counth);
System.out.println ("Number of letters" +counte);
}
}
"Program 8"? Title: The value of S=A+AA+AAA+AAAA+AA...A, where a is a number. For example 2+22+222+2222+22222 (there are 5 numbers added at this time), several numbers are added with keyboard control.
1. Program Analysis: The key is to calculate the value of each item.
Import java.io.;
public class Sumloop {
public static void Main (string[] args) throws IOException
{
int s=0;
String output= "";
BufferedReader Stadin = new BufferedReader (new InputStreamReader (system.in));
System.out.println ("Please enter a value");
String input =stadin.readline ();
for (int i =1;i<=integer.parseint (input); i++)
{
Output+=input;
int a=integer.parseint (output);
S+=a;
}
System.out.println (s);
}
}
Another solution:
Import java.io.
;
public class Sumloop {
public static void Main (string[] args) throws IOException
{
int s=0;
int n;
int t=0;
BufferedReader Stadin = new BufferedReader (new InputStreamReader (system.in));
String input = Stadin.readline ();
N=integer.parseint (input);
for (int i=1;i<=n;i++) {
T=t*10+n;
S=s+t;
System.out.println (t);
}
System.out.println (s);
}
}
"Program 9"? Title: If a number is exactly equal to the sum of its factors, this number is called the "end number". such as 6=1+2+3. Programming? Find out all the numbers within 1000.
public class Wanshu {
public static void Main (string[] args)
{
int s;
for (int i=1;i<=1000;i++)
{
s=0;
for (int j=1;j<i;j++)
if (i% j==0)
S=s+j;
if (s==i)
System.out.print (i+ "");
}
System.out.println ();
}
}
"Program 10" title: A ball from 100 meters height of freedom falling, each landing back to the original height of half; fall again, beg for it? How many meters are there in the 10th time when landing? How high is the 10th time rebound??
public class Ex10 {
public static void Main (string[] args)
{
Double s=0;
Double t=100;
for (int i=1;i<=10;i++)
{
s+=t;
T=T/2;
}
System.out.println (s);
System.out.println (t);

}
}
"Program 11"? Title: There are 1, 2, 3, 4 numbers, can make up how many different and no repetition of the number of three digits? How much is it??
1. Program Analysis: Can be filled in the hundred, 10 digits, digit digits are 1, 2, 3, 4. Make up all the permutations before you go? Out of the arrangement that does not satisfy the condition.?
public class Wanshu {
public static void Main (string[] args)
{
int i=0;
int j=0;
int k=0;
int t=0;
for (i=1;i<=4;i++)
for (j=1;j<=4;j++)
for (k=1;k<=4;k++)
if (i!=j && j!=k && i!=k)
{t+=1;
System.out.println (i100+j10+K);
}
System.out.println (t);
}
}
"Program 12"? Title: the bonus paid by the enterprise according to the profit commission. Profit (I) less than or equal to $100,000, the bonus can be raised by 10%, the profit is higher than $100,000, less than $200,000, less than 100,000 of the portion of the 10% commission, higher than the portion of 100,000 yuan, Cocoa Commission 7.5%, 200,000 to 400,000, higher than 200,000 yuan of the portion, can commission 5% ; Between 400,000 and 600,000 is higher than the portion of 400,000 yuan, can commission 3%, 600,000 to 1 million, higher than 600,000 yuan portion, can commission 1.5%, higher than 1 million yuan, the portion of more than 1 million yuan by 1% Commission, from the keyboard input month profit I, the total bonus should be issued??
1. Program Analysis: Please use the axis to demarcation, positioning. Note that the bonus definition should be defined as the growth integral type.
Import java. util.;
public class Test {
public static void Main (String[]args) {
Double sum;//declare the bonus of the variable should be to be stored
Scanner input =new Scanner (system.in);//import Scanner
System.out.print ("Enter monthly Profit");
Double lirun=input. nextdouble ();//Enter profit from console
if (lirun<=100000) {
Sum=lirun
0.1;
}else if (lirun<=200000) {
Sum=10000+lirun0.075;
}else if (lirun<=400000) {
Sum=17500+lirun
0.05;
}else if (lirun<=600000) {
Sum=lirun0.03;
}else if (lirun<=1000000) {
Sum=lirun
0.015;
} else{
sum=lirun*0.01;
}
System.out.println ("Should be's bonus is" +sum);
}
}
The code behind the rest of the situation can be perfected by the reader itself.

"Program 13"?
Title: An integer, which plus 100 is a complete square number, plus 168 is a complete square number, what is the number??
1. Procedure analysis: In 100,000 to judge, the number plus 100 after the root, and then the number plus 268 after the root, if the result of the root satisfies the following conditions, that is the result. Please see the specific analysis:?
public class Test {
public static void Main (String[]args) {
Long k=0;
for (k=1;k<=100000l;k++)
if (Math.floor (Math.sqrt (k+100)) ==math.sqrt (k+100) && Math.floor (Math.sqrt (k+168)) ==math.sqrt (k+168))
System.out.println (k);
}
}
"Program 14" title: Enter a certain day of the year, Judge this day is the first of the year??
1. Procedure analysis: Take March 5 as an example, should first add up the first two months, and then add 5 days that is the first day of the year, special cases, leap years and enter the month greater than 3 o'clock need to consider more than one day.
Import Java.util.;
public class Test {
public static void Main (String[]args) {
int day=0;
int month=0;
int year=0;
int sum=0;
int leap;
System.out.print ("Please enter the year, month, day \ n");
Scanner input = new Scanner (system.in);
Year=input.nextint ();
Month=input.nextint ();
Day=input.nextint ();
Switch (month)/
Calculate the total number of days before a month/
{
Case 1:
Sum=0;break;
Case 2:
Sum=31;break;
Case 3:
Sum=59;break;
Case 4:
Sum=90;break;
Case 5:
Sum=120;break;
Case 6:
Sum=151;break;
Case 7:
Sum=181;break;
Case 8:
Sum=212;break;
Case 9:
Sum=243;break;
Case 10:
Sum=273;break;
Case 11:
Sum=304;break;
Case 12:
Sum=334;break;
Default
SYSTEM.OUT.PRINTLN ("Data Error");
}
Sum=sum+day; /
Plus the number of days in a day/
if (year%400==0| | (year%4==0&&year%100!=0)) /
Judging is not a leap year/
Leap=1;
Else
Leap=0;
if (leap==1 && month>2)/
If a leap year and the month is greater than 2, the total number of days should be one day/
sum++;
System.out.println ("It's The Day:" +sum);
}
}
"Program 15" title: Enter three integers x, y, Z, please put these three numbers from small to large output.
1. Procedure analysis: We find a way to put the smallest number on X, first compare x with Y, if x> y will be the value of x and Y to Exchange, and then with X and Z to compare, if X> Z will be x and Z of the value of the exchange, this can make x minimum.
Import Java.util.
;
public class Test {
public static void Main (String[]args) {
int i=0;
int j=0;
int k=0;
int x=0;
System.out.print ("Please enter three number \ n");
Scanner input = new Scanner (system.in);
I=input.nextint ();
J=input.nextint ();
K=input.nextint ();
if (I&GT;J)
{
X=i;
I=j;
J=x;
}
if (i>k)
{
X=i;
I=k;
K=x;
}
if (j>k)
{
X=j;
J=k;
K=x;
}
System.out.println (i+ "," +j+ "," +k ");
}
}
"Program 16" title: Output 99 formulas.?
1. Program Analysis: Branch and column considerations, a total of 9 rows 9 columns, I control row, J control column.
public class Jiujiu {
public static void Main (string[] args)
{
int i=0;
int j=0;
for (i=1;i<=9;i++)
{for (j=1;j<=9;j++)
System.out.print (i+ "
"+j+" = "+i*j+" \ t ");
System.out.println ();
}

}

}
Product with no repetition (lower triangle)
public class Jiujiu {
public static void Main (string[] args)
{
int i=0;
int j=0;
for (i=1;i<=9;i++)
{for (j=1;j<=i;j++)
System.out.print (i+ ""+j+" = "+ij+ "\ t");
System.out.println ();
}
}
}
Upper Triangle
public class Jiujiu {
public static void Main (string[] args)
{
int i=0;
int j=0;
for (i=1;i<=9;i++)
{for (j=i;j<=9;j++)
System.out.print (i+ ""+j+" = "+ij+ "\ t");
System.out.println ();
}
}
}
"Program 17"? Title: Monkey Eat Peach problem: The first day of monkeys to take off a number of peaches, immediately ate half, not addicted, and eat one more? The next morning he ate half of the remaining peaches and ate one more. After every morning, the day before the rest? Half of the zero one. When I want to eat again in the morning of the 10th day, I see only one peach left. The first day of the total pick how much.? N
1. Procedure analysis: Adopt the method of reverse thinking, infer from the backward forward.
public class Monkeys eat peach {1 n/2-1
2 (n/2-1)/2-1
3 ((n/2-1)/2-1)/2-1
4 (((n/2-1)/2-1)/2-1)/2-1
static int Total (Int. day) {
if (day = = 10) {10 1
return 1; 9 (+)2
} 8
else{
Return (Total (day+1) +1)
2;
}
}
public static void Main (string[] args)
{
System.out.println (Total (1));
}
}
"Program 18"? Title: Two table tennis team to play, each out three people. Team A for A,b,c three, team B for X, Y, z three people. Have drawn lots to determine the contest list. Someone asked the team for a list of matches. A says he does not compare with X, C says he does not compare with x,z, please compile the procedure to find out the list of the three teams.
1. Procedure analysis: The method of judging primes: to remove 2 to sqrt (this number) by a number, if it can be divided evenly,? Indicates that the number is not a prime, and vice versa.
Import java.util.ArrayList;
public class Pingpang {
String A,b,c;
public static void Main (string[] args) {
String[] op = {"X", "Y", "Z"};
Arraylist<pingpang> arraylist=new arraylist<pingpang> ();
for (int i = 0; i < 3; i++)
for (int j = 0; J < 3; J + +)
for (int k = 0; k < 3; k++) {
Pingpang a=new Pingpang (Op[i],op[j],op[k]);
if (!a.a.equals (A.B) &&!a.b.equals (A.C) &&!a.a.equals ("X")
&&!a.c.equals ("x") &&!a.c.equals ("Z")) {
Arraylist.add (a);
}
}
for (Object a:arraylist) {
System.out.println (a);
}
}
Public Pingpang (String A, string B, string c) {
Super ();
THIS.A = A;
this.b = b;
THIS.C = C;br/>}
@Override
TODO auto-generated Method Stub
Return "A's opponent is" +a+ "," + "B's opponent is" +b+ "," + "C's opponent is" +c+ "\ n";
}
}
"Program 19"? Title: Print out the case (diamond)?

    • ?
      *?
      * * ?
      * * * ?
      * * ?
      *
      ?
    • ?
      1. Program Analysis: First the graph into two parts to see, the first four lines a rule, after three lines a rule, the use of double? For loop, the first layer control row, the second Layer control column.
      2.?
      Triangle:
      public class STARTG {
      public static void Main (String [] args)
      {
      int i=0;
      int j=0;
      for (i=1;i<=4;i++) {
      for (j=1;j<=2
      i-1;j++)
      System.out.print ("");
      System.out.println ("");
      }
      for (i=4;i>=1;i--) {
      for (j=1;j<=2
      i-3;j++)
      System.out.print ("*");
      System.out.println ("");
      }
      }
      }

Rhombic:
public class Startg {
public static void Main (String [] args)
{
int i=0;
int j=0;
for (i=1;i<=4;i++)
{
for (int k=1; k<=4-i;k++)
System.out.print ("");
For (j=1;j<=2i-1;j++)
System.out.print ("
");
System.out.println ("");
}
for (i=4;i>=1;i--)
{
for (int k=1; k<=5-i;k++)
System.out.print ("");
For (j=1;j<=2i-3;j++)
System.out.print ("
");
System.out.println ("");
}
}
}

"Program 20"? Title: There is a fractional sequence: 2/1,3/2,5/3,8/5,13/8,21/13 ... to find out the sum of the first 20 items of this series.
1. Program Analysis: Please grasp the molecular and the denominator of the law of change.
public class Test20 {
public static void Main (string[] args) {
float fm = 1f;
float FZ = 1f;
float temp;
float sum = 0f;
for (int i=0;i<20;i++) {
TEMP = FM;
FM = FZ;
FZ = FZ + temp;
sum + = FZ/FM;
SYSTEM.OUT.PRINTLN (sum);
}
SYSTEM.OUT.PRINTLN (sum);
}
}

"Java Classic algorithm 40 questions (top)"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.