Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 49 additions & 33 deletions AP1403 - WarmUp/src/main/java/Exercises.java
Original file line number Diff line number Diff line change
@@ -1,48 +1,64 @@
public class Exercises {

/*
complete this function to check if the input number is prime or not
*/
public boolean isPrime(long n) {
// todo
return false;
}
if (n <= 1) {
return false;
}
for (long i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;

/*
implement an algorithm to find out the index of input number in a fibonacci sequence starting from 0, 1
e.g. 0, 1, 1, 2, 3, 5, ...
indices start from 0, e.g. 3 is the index 4 of this sequence
if the input is not a fibonacci number with description above, return -1
*/
public long fibonacciIndex(long n) {
// todo
return -1;
}

/*
you should create a triangle with "*" and return a two-dimensional array of characters based on that
the triangle's area is empty, which means some characters should be " "
public long fibonacciIndex(long n) {
if (n < 0) return -1;
long a = 0, b = 1;
long index = 0;

example 1, input = 3:
*
**
***
while (a < n) {
long temp = a;
a = b;
b = temp + b;
index++;
}

example 2, input = 5:
*
**
* *
* *
*****
return (a == n) ? index : -1;
}

the output has to be a two-dimensional array of characters, so don't just print the triangle!
*/
public char[][] generateTriangle(int n) {
// todo
return null;
char[][] triangle = new char[n][n];

for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
if (i == n - 1 || j == 0 || j == i) {
triangle[i][j] = '*';
} else {
triangle[i][j] = ' ';
}
}
}

return triangle;
}

public static void main(String[] args) {
// you can test your code here, but then it should be checked with test cases
Exercises ex = new Exercises();


System.out.println(ex.isPrime(7)); // true
System.out.println(ex.isPrime(10)); // false


System.out.println(ex.fibonacciIndex(3)); // 4
System.out.println(ex.fibonacciIndex(6)); // -1


char[][] triangle = ex.generateTriangle(5);
for (char[] row : triangle) {
System.out.println(new String(row));
}
}
}