Jupyter at Bryn Mawr College |
|||
Public notebooks: /services/public/dblank / CS110 Intro to Computing / 2015-Fall / Notes |
Functions that return true or false (boolean values).
boolean isPrime(int number) {
// if number is evenly divided by any number less than number
// (except 1) then it is prime
// otherwise, not prime
for (int i = 2; i < number; i++) {
if ((number % i) == 0) {
return false;
}
}
return true;
}
void setup() {
println("isPrime(100): " + isPrime(100));
println("isPrime(101): " + isPrime(101));
println("isPrime(107): " + isPrime(107));
}
Greatest common divisor: the largest positive integer that divides all of the numbers without a remainder. For example, the GCD of 8 and 12 is 4.
Euclid's Algorithm (after https://en.wikipedia.org/wiki/Greatest_common_divisor):
Example:
1. Let a = 8, and b = 12 2. Neither is zero 3. a = 4 (12 - 8), b = 12 4. a = 4, b = 8 (12 - 4) 5. a = 4, b = 4 (8 - 4) 6. a = 0 (4 - 4), b = 4 6. return 4
int gcd(int a, int b) {
if (a == 0) // base case
return b;
else if (b == 0) // base case
return a;
else if (a > b)
return gcd(a - b, b);
else //
return gcd(a, b - a);
}
void setup() {
println("gcd(8, 12): " + gcd(8, 12));
println("gcd(3, 2): " + gcd(3, 2));
}
boolean isLeapyear(int year) {
// if a year is evenly divided by 100
// but it is not evenly divided by 400
// it is a leapyear
// else if a year is evenly divided by 4, it is a leap year
// otherwise, not a leapyear
return true;
}
void setup() {
println("isLeapyear(2000): " + isLeapyear(2000) + " (should be true)");
println("isLeapyear(1904): " + isLeapyear(1904) + " (should be true)");
println("isLeapyear(1900): " + isLeapyear(1900) + " (should be false)");
println("isLeapyear(1901): " + isLeapyear(1901) + " (should be false)");
}