All topics

Square Root

A number is square root of if

Most programming languages have an in-built sqrt function. But it can be easily calculated using binary search.

float sqrt(n) {
    low = 0.0;
    high = (float)n+1;
    while ((high-low) > 0.00001) {
        mid = (low+high) / 2;
        if (mid*mid < n) {
            low = mid;
        }
        else {
            high = mid;
        }
    }
    return low;
}

Note that we do not check high - low == some_value This is because we never equate float values. Instead, we use a small epsilon value and use that as an error tolerance.

Newton Raphson Method:

#include <stdio.h>
// Function to get absolute value of the number given by user.
float absolute(float num)
{
    if(num < 0){
        num = -num;
    }
    return num;
}
// Function to calculate square root of the number using Newton-Raphson method
float square_root(int x)
{
    const float difference = 0.00001;
    float guess = 1.0;
    while(absolute(guess * guess - x) >= difference){
        guess = (x/guess + guess)/2.0;
    }
    return guess;
}

int main()
{
    int number;
    float root;
    printf("Enter a number: ");
    scanf("%i", &number);
    root = square_root(number);
    printf("The square root of %i is: %f", number, root);
    return 0;
}
 
Related challenge for Square Root
Go to Top

Ceil Floor

Float values can be rounded to their floor values and ceil values. This is not rounding as rounding happens to the nearest integer, while in floor and ceil we specify which nearest integer we are rounding to.

Most programming languages have in-built floor and ceil functions.

floor(5.9) = 5
ceil(1.1) = 2
floor(-1.1) = -2
ceil(-2.1) = -2

C ++ Implementation :

#include <iostream>
#include <cmath> // library support is needed
using namespace std ;
int main(){
    cout << floor(5.9) << endl ;
    cout << ceil(1.1) << endl ;
    cout << floor(-1.1) << endl ;
    cout << ceil(-2.1) << endl ;
    return 0 ; 
}

Python Implementation :

import math # libraray support is needed
print int(math.floor(5.9))
print int(math.ceil(1.1))
print int(math.floor(-1.1))
print int(math.ceil(-2.1))
 
Go to Top
  1. Challenge Walkthrough
    Let's walk through this sample challenge and explore the features of the code editor.1 of 6
  2. Review the problem statement
    Each challenge has a problem statement that includes sample inputs and outputs. Some challenges include additional information to help you out.2 of 6
  3. Choose a language
    Select the language you wish to use to solve this challenge.3 of 6
  4. Enter your code
    Code your solution in our custom editor or code in your own environment and upload your solution as a file.4 of 6
  5. Test your code
    You can compile your code and test it for errors and accuracy before submitting.5 of 6
  6. Submit to see results
    When you're ready, submit your solution! Remember, you can go back and refine your code anytime.6 of 6
  1. Check your score