Skip to content
Closed
Show file tree
Hide file tree
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
38 changes: 38 additions & 0 deletions Maths/CollatzSequence.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package Maths;

/**
* The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined as follows:
* start with any positive integer n.
* Then each term is obtained from the previous term as follows:
* if the previous term is even, the next term is one half of the previous term.
* If the previous term is odd, the next term is 3 times the previous term plus 1.
* The conjecture is that no matter what value of n, the sequence will always reach 1.
* <a href="https://www.wikiwand.com/en/Collatz_conjecture">https://www.wikiwand.com/en/Collatz_conjecture</a>
*/
public class CollatzSequence {
/**
* Runs the sequence starting on the value passed in, stopping when the sequence reaches 1.
* @param start initial value the sequence is run on.
*/
public static void collatz(int start) {
while (start != 1) {
System.out.print(start + " ");
if (start % 2 == 0) {
start = start / 2;
}
else {
start = 3 * start + 1;
}
}
System.out.print(start);
System.out.println();
}

/**
* Driver code
*/
public static void main(String[] args) {
collatz(3); // 3, 10, 5, 16, 8, 4, 2, 1
collatz(6); // 6, 3, 10, 5, 16, 8, 4, 2, 1
}
}
35 changes: 35 additions & 0 deletions Maths/HeronsFormula.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package Maths;

/**
* Heron's formula gives the area of a triangle when the length of all three sides are known.
* <a href="https://www.wikiwand.com/en/Heron%27s_formula">https://www.wikiwand.com/en/Heron%27s_formula</a>
*/

public class HeronsFormula {
/**
*
* @param a a side of the triangle
* @param b a side of the triangle
* @param c a side of the triangle
* @return the calculated area of the triangle using Heron's formula
*/
public static double calculateArea(double a, double b, double c) {
/* Checks if the three sides can really represent a triangle */
if ((a + b < c) || (b + c < a) || (a + c < b)) {
return 0.0;
}

double halfPerimeter = (a + b + c) / 2.0;
double area = Math.sqrt(halfPerimeter * (halfPerimeter - a) * (halfPerimeter - b) * (halfPerimeter - c));

return area;
}
/**
* Driver code
*/
public static void main(String[] args) {
assert calculateArea(5, 5, 5) == 10.825317547305483;
assert calculateArea(4, 4, 5) == 7.806247497997997;
assert calculateArea(10, 2, 3) == 0.0;
}
}