algorithms with-java-1.0
DESCRIPTION
TRANSCRIPT
![Page 1: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/1.jpg)
Solve problems with Java codeSolve problems with Java code
Algorithms with Algorithms with JavaJava
![Page 2: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/2.jpg)
Sum 1..N – ExampleSum 1..N – Example
Calculate and print the sum of the first N Calculate and print the sum of the first N positive numberspositive numbers
2
Scanner input = new Scanner(System.in);Scanner input = new Scanner(System.in);System.out.print("n = ");System.out.print("n = ");int n = input.nextInt();int n = input.nextInt();int num = 1;int num = 1;int sum = 1;int sum = 1;
System.out.print("The sum 1");System.out.print("The sum 1");while (num < n) {while (num < n) { num++;num++; sum += num;sum += num; System.out.printf("+%d", num);System.out.printf("+%d", num);}}System.out.printf(" = %d%n", sum);System.out.printf(" = %d%n", sum);
![Page 3: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/3.jpg)
Calculating Sum 1..NCalculating Sum 1..NLive DemoLive Demo
![Page 4: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/4.jpg)
Prime Number – ExamplePrime Number – Example
Checking if a number is prime or notChecking if a number is prime or not
4
Scanner input = new Scanner(System.in);Scanner input = new Scanner(System.in);System.out.print("Enter a positive integer: ");System.out.print("Enter a positive integer: ");int num = input.nextInt();int num = input.nextInt();int divider = 2;int divider = 2;int maxDivider = (int) Math.sqrt(num);int maxDivider = (int) Math.sqrt(num);boolean prime = true;boolean prime = true;while (prime && (divider <= maxDivider)) {while (prime && (divider <= maxDivider)) { if (num % divider == 0) {if (num % divider == 0) { prime = false;prime = false; }} divider++;divider++;}}System.out.println("Prime? " + prime);System.out.println("Prime? " + prime);
![Page 5: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/5.jpg)
Checking If a Number Is Checking If a Number Is PrimePrimeLive DemoLive Demo
![Page 6: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/6.jpg)
Using Using breakbreak Operator Operator
breakbreak operator exits the inner-most loop operator exits the inner-most loop
6
Scanner input = new Scanner(System.in);Scanner input = new Scanner(System.in);int n = input.nextInt();int n = input.nextInt();
// "long" is the biggest integer type// "long" is the biggest integer typelong factorial = 1;long factorial = 1;
// Perform an infinite loop// Perform an infinite loopwhile (true) {while (true) { if (n == 1) {if (n == 1) { break;break; }} factorial *= n;factorial *= n; n--;n--;}}System.out.println("n! = " + factorial);System.out.println("n! = " + factorial);
![Page 7: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/7.jpg)
Calculating FactorialCalculating FactorialLive DemoLive Demo
![Page 8: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/8.jpg)
Factorial – ExampleFactorial – Example
Calculating N factorialCalculating N factorial
8
Scanner input = new Scanner(System.in);Scanner input = new Scanner(System.in);System.out.print("n = ");System.out.print("n = ");int n = input.nextInt();int n = input.nextInt();long factorial = 1;long factorial = 1;
do {do { factorial *= n;factorial *= n; n--;n--;}}while (n > 0);while (n > 0);
System.out.println("n! = " + factorial);System.out.println("n! = " + factorial);
![Page 9: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/9.jpg)
Factorial (do ... while)Factorial (do ... while)Live DemoLive Demo
![Page 10: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/10.jpg)
RecursionRecursion
Calling a Method by ItselfCalling a Method by Itself
![Page 11: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/11.jpg)
What is Recursion?What is Recursion?
• Recursion is calling a method by itselfRecursion is calling a method by itself
• Very powerful technique for implementing Very powerful technique for implementing combinatorial algorithmscombinatorial algorithms
• Recursion should haveRecursion should have
• Direct or indirect recursive callsDirect or indirect recursive calls
• The method calls itself directly or through The method calls itself directly or through other methodsother methods
• Exit criteria (bottom)Exit criteria (bottom)
• Prevent infinite recursionPrevent infinite recursion
![Page 12: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/12.jpg)
Factorial – ExampleFactorial – Example
• N! (N Factorial)N! (N Factorial)
• N! = N * (N – 1)! for N >= 0 and 0! = 1N! = N * (N – 1)! for N >= 0 and 0! = 1
• 5! = 5 * 4! or 5 * 4 * 3 * 2 * 1 * 1 = 1205! = 5 * 4! or 5 * 4 * 3 * 2 * 1 * 1 = 120
• 4! = 4 * 3! or 4 * 3 * 2 * 1 * 1 = 244! = 4 * 3! or 4 * 3 * 2 * 1 * 1 = 24
• 3! = 3 * 2! or 3 * 2 * 1 * 1 = 63! = 3 * 2! or 3 * 2 * 1 * 1 = 6
• 2! = 2 * 1! or 2 * 1 * 1 = 22! = 2 * 1! or 2 * 1 * 1 = 2
• 1! = 1 * 0! or 1 * 1 = 11! = 1 * 0! or 1 * 1 = 1
• 0! = 10! = 1
![Page 13: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/13.jpg)
Factorial – ExampleFactorial – Example
• Calculating factorial:Calculating factorial:
• 0! = 10! = 1
• n! = n* (n-1)!, n>0n! = n* (n-1)!, n>0
• Don't do this at home!Don't do this at home!
• Use iteration insteadUse iteration instead
Recursive call: Recursive call: the method calls the method calls
itselfitself
Recursive call: Recursive call: the method calls the method calls
itselfitself
The bottom of The bottom of the recursionthe recursionThe bottom of The bottom of the recursionthe recursion
public public static int static int ffactorial(int n)actorial(int n) {{ if (n == 0) if (n == 0) return 1; return 1; else else return n * return n * ffactorial(n - 1); actorial(n - 1); } }
![Page 14: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/14.jpg)
Product[N..M] – ExampleProduct[N..M] – Example
Calculating the product of all numbers in Calculating the product of all numbers in the interval [n..m]:the interval [n..m]:
14
int n = input.nextInt();int n = input.nextInt();int m = input.nextInt();int m = input.nextInt();
int num = n;int num = n;long product = 1;long product = 1;
do {do { product *= num;product *= num; num++;num++;} } while(num <= m);while(num <= m);System.out.println("product[n..m] = " + product);System.out.println("product[n..m] = " + product);
![Page 15: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/15.jpg)
Product of the Numbers Product of the Numbers in the Interval [n..m]in the Interval [n..m]
Live DemoLive Demo
![Page 16: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/16.jpg)
N^M – ExampleN^M – Example
Calculating n^mCalculating n^m
16
Scanner input = new Scanner(System.in);Scanner input = new Scanner(System.in);int n = input.nextInt();int n = input.nextInt();int m = input.nextInt();int m = input.nextInt();long result = 1;long result = 1;
for (int i = 0; i < m; i++) {for (int i = 0; i < m; i++) { result *= n;result *= n;}}
System.out.println("n^m = " + result);System.out.println("n^m = " + result);
![Page 17: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/17.jpg)
Calculating N^MCalculating N^MLive DemoLive Demo
![Page 18: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/18.jpg)
Using Using continuecontinue Operator Operator
continuecontinue operator ends iteration of the operator ends iteration of the inner-most loopinner-most loop
Example: Sum odd numbers p in [1, n] that Example: Sum odd numbers p in [1, n] that are not divisors of 7:are not divisors of 7:
18
int n = input.nextInt();int n = input.nextInt();int sum = 0;int sum = 0;
for (int i = 1; i <= n; i += 2) {for (int i = 1; i <= n; i += 2) { if (i % 7 == 0)if (i % 7 == 0) continue;continue; sum += i;sum += i;}}System.out.println("sum = " + sum);System.out.println("sum = " + sum);
![Page 19: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/19.jpg)
Using Using continuecontinue Operator OperatorLive DemoLive Demo
![Page 20: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/20.jpg)
Nested LoopsNested LoopsUsing Loop Inside a LoopUsing Loop Inside a Loop
![Page 21: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/21.jpg)
What Is Nested Loop?What Is Nested Loop?
A composition of loops is called a nested A composition of loops is called a nested looploop
Example:Example:
21
for (initialization; test; update) {for (initialization; test; update) { for (initialization; test; update) {for (initialization; test; update) { statements;statements; }} … …} }
![Page 22: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/22.jpg)
Nested LoopsNested LoopsExamplesExamples
![Page 23: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/23.jpg)
Triangle – ExampleTriangle – Example
Print the following triangle on the console:Print the following triangle on the console:
11
1 21 2
……
1 2 3 ... n1 2 3 ... n
23
int n = input.nextInt();int n = input.nextInt();for (int i = 1; i <= n; i++) {for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) {for (int j = 1; j <= i; j++) { System.out.print(j + " ");System.out.print(j + " "); }} System.out.println();System.out.println();}}
![Page 24: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/24.jpg)
TriangleTriangleLive DemoLive Demo
![Page 25: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/25.jpg)
Primes[N, M] – ExamplePrimes[N, M] – Example
Print all prime numbers in [n, m]Print all prime numbers in [n, m]
25
int n = input.nextInt();int n = input.nextInt();int m = input.nextInt();int m = input.nextInt();for (int num = n; num <= m; num++) {for (int num = n; num <= m; num++) { boolean prime = true;boolean prime = true; int divider = 2;int divider = 2; int maxDivider = (int) Math.sqrt(num);int maxDivider = (int) Math.sqrt(num); while (divider <= maxDivider) {while (divider <= maxDivider) { if (num % divider == 0) {if (num % divider == 0) { prime = false;prime = false; break;break; }} divider++;divider++; }} if (prime) {if (prime) { System.out.printf("%d ", num);System.out.printf("%d ", num); }}}}
![Page 26: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/26.jpg)
Primes in Range [n, m]Primes in Range [n, m]Live DemoLive Demo
![Page 27: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/27.jpg)
Loops – More ExamplesLoops – More Examples
![Page 28: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/28.jpg)
Nested Loops – ExamplesNested Loops – Examples
Print all four digit numbers ABCD such that Print all four digit numbers ABCD such that A+B = C+D (happy numbers)A+B = C+D (happy numbers)
28
for (int a = 1; a <= 9; a++) {for (int a = 1; a <= 9; a++) { for (int b = 0; b <= 9; b++) {for (int b = 0; b <= 9; b++) { for (int c = 0; c <= 9; c++) {for (int c = 0; c <= 9; c++) { for (int d = 0; d <= 9; d++) {for (int d = 0; d <= 9; d++) { if ((a + b) == (c + d)) {if ((a + b) == (c + d)) { System.out.printf("%d,%d,%d,%d", System.out.printf("%d,%d,%d,%d", a, b, c, d);a, b, c, d);
}}}}
}} }}}}
Can you improve Can you improve this algorithm to this algorithm to
use only 3 loops?use only 3 loops?
Can you improve Can you improve this algorithm to this algorithm to
use only 3 loops?use only 3 loops?
![Page 29: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/29.jpg)
Happy NumbersHappy NumbersLive DemoLive Demo
![Page 30: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/30.jpg)
TOTO 6/49 – ExamplesTOTO 6/49 – Examples
Print all combinations from TOTO 6/49Print all combinations from TOTO 6/49
30
for (int i1 = 1; i1 <= 44; i1++)for (int i1 = 1; i1 <= 44; i1++)
for (int i2 = i1 + 1; i2 <= 45; i2++)for (int i2 = i1 + 1; i2 <= 45; i2++)
for (int i3 = i2 + 1; i3 <= 46; i3++)for (int i3 = i2 + 1; i3 <= 46; i3++)
for (int i4 = i3 + 1; i4 <= 47; i4++)for (int i4 = i3 + 1; i4 <= 47; i4++)
for (int i5 = i4 + 1; i5 <= 48; i5++)for (int i5 = i4 + 1; i5 <= 48; i5++)
for (int i6 = i5 + 1; i6 <= 49; i6++)for (int i6 = i5 + 1; i6 <= 49; i6++)
System.out.printf(System.out.printf(
"%d %d %d %d %d %d%n","%d %d %d %d %d %d%n",
i1, i2, i3, i4, i5, i6);i1, i2, i3, i4, i5, i6);
How long will it How long will it take to finish this?take to finish this?
How long will it How long will it take to finish this?take to finish this?
![Page 31: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/31.jpg)
TOTO 6/49TOTO 6/49Live DemoLive Demo
![Page 32: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/32.jpg)
SummarySummary
Loops could solve different problemsLoops could solve different problems Recursion could be handy as wellRecursion could be handy as well We can use nested loops to implement We can use nested loops to implement
more complex logicmore complex logic We can use We can use continuecontinue and and break break operators operators
to control the loop executionto control the loop execution More to come with arrays' manipulationMore to come with arrays' manipulation
32
![Page 33: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/33.jpg)
Exercises Exercises
1.1. Write a program that prints all the numbers Write a program that prints all the numbers from 1 to N.from 1 to N.
2.2. Write a program that prints all the numbers Write a program that prints all the numbers from 1 to N, that are not divisible by 3 and 7.from 1 to N, that are not divisible by 3 and 7.
3.3. Write a program that reads from the console a Write a program that reads from the console a sequence of N integer numbers and returns sequence of N integer numbers and returns the minimal and maximal of them.the minimal and maximal of them.
4.4. Write a program that calculates N!/K! for Write a program that calculates N!/K! for given N and K (1<N<K).given N and K (1<N<K).
33
![Page 34: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/34.jpg)
Exercises (3) Exercises (3)
1.1. Write a program that reads a number N and Write a program that reads a number N and calculates the sum of the first N members of calculates the sum of the first N members of the sequence of Fibonacci: the sequence of Fibonacci: 0, 1, 1, 2, 3, 5, 8, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, …13, 21, 34, 55, 89, 144, 233, 377, …
2.2. In the combinatorial mathematics, the In the combinatorial mathematics, the Catalan numbers are calculated by the Catalan numbers are calculated by the following formula:following formula:
Write a program to calculate the Catalan Write a program to calculate the Catalan number by given N.number by given N.
34
![Page 35: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/35.jpg)
Exercises (4)Exercises (4)
1.1. Write a program that reads from the console Write a program that reads from the console a positive integer number N (N < 20) and a positive integer number N (N < 20) and outputs a matrix like the following:outputs a matrix like the following:
N = 3N = 3 N = 4N = 4
35
1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7
1 2 3
2 3 4
3 4 5
![Page 36: Algorithms with-java-1.0](https://reader034.vdocuments.site/reader034/viewer/2022051108/545c575db0af9f12318b47c1/html5/thumbnails/36.jpg)
Exercises (5)Exercises (5)
36
1. Write a program that calculates for given N how many trailing zeros present at the end of the number N!. Examples:
N = 10 N! = 3628800 2
N = 20 N! = 2432902008176640000 4
Does your program work for N = 50 000?
Hint: The trailing zeros in N! are equal to the number of its prime divisors 5. Think why!