Java 101 Chapter 4

int product(int a, int b) {
int sum = 0;
for (int i= 0; i < b; i++) {
sum += a;
}
return sum;
}
int power(int a, int b) { 
if (b < 0) {
return 0; //error
} else if (b == 0) {
return 1;
} else {
return a* power(a, b - 1);
}
}
int sqrt(int n) {
return sqrt_helper(n, 1, n);
}
int sqrt_helper(int n, int min, int max) {
if (max < min) return -1; //no square root
int guess = (min + max)/2;
if (guess *guess == n) { // found it!
return guess;
}
else if (guess * guess < n) { //too low
return sqrt_helper(n, guess + 1, max); //try higher
} else { //too high
return sqrt_helper(n, min, guess - l); //try lower
}
}
int sumDigits(int n) { 
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}

--

--

--

I am en electronics engineer, graduated from ITESM. Experienced working as functional validation and software development.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

The magic power of UNPIVOT in SQL

TryHackMe: [Day 2] Web Exploitation Elf HR Problems

Some core concept of Python

Meet Our First Apprentices

Tarsplit: A Utility to Split Tarballs Into Multiple Parts

Your First Websocket Client in R

Explore the possibilities with hundreds of domain extensions — {link} -

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jesus PF

Jesus PF

I am en electronics engineer, graduated from ITESM. Experienced working as functional validation and software development.

More from Medium

OOps concepts

Main principles in Java OOP (Object-Oriented Programming)

Extra-Strength Methods

A Walk Through to the Executor Framework in Java.