How to Find Ceil and Floor Solution In C++/Java/Python/JS
How to find Ceil and Floor Problem Description
Given a real number x, find:
Ceil of x: The smallest integer that is greater than or equal to x.
Floor of x: The largest integer that is less than or equal to x.
You must return both values as output.

Examples:
Input: x = 4.3
Output: Ceil: 5, Floor: 4
Explanation:
The smallest integer ≥ 4.3 is 5.
The largest integer ≤ 4.3 is 4.
Input: x = -2.7
Output: Ceil: -2, Floor: -3
Explanation:
The smallest integer ≥ -2.7 is -2.
The largest integer ≤ -2.7 is -3.
Input: x = 7.0
Output: Ceil: 7, Floor: 7
Explanation:
Since 7.0 is already an integer, Ceil(7.0) = Floor(7.0) = 7.
Understanding Floor and Ceil
What is Floor?
Alright, let’s imagine a building — a tall one with floors: ground floor, 1st floor, 2nd floor, 3rd floor, and so on.
Now, suppose each floor is exactly 1.0 height tall. So, from the 3rd floor to the 4th floor is like going from height 3.0 to 4.0.
Now let’s say you’re climbing up the stairs, and you stop somewhere between the 3rd and 4th floor — maybe at 3.7 height. You haven’t reached the 4th floor yet, right? You’re still on your way. So if someone asks, “Which floor are you on?” — the answer is: you’re still on the 3rd floor, because you haven’t reached ot crossed 4.0.
That’s exactly how floor of a number works in math.
The floor of a number is the biggest full number you’ve reached without going past it.
So:
- If you’re at 3.7, your floor is 3 — still on the 3rd floor.
- If you’re at 2.3, you’re on the 2nd floor.
- At 5.9, you’re on the 5th floor — almost at 6, but not yet.
- If you land exactly at 6.0, then you’re on the 6th floor.
Now let’s think about going underground — like moving up from the basement floors to the ground floor.
If you’re at -1.4, you’re between , but since you passed -2 on your way up, you’re still on -2nd floor.
So just like in real buildings where each floor is 1.0 tall, the floor of any number is simply the last full floor you’ve reached — even if you’re somewhere in between. You never say you're on the next floor until you've fully reached it!

Example 1: Floor of 4.7
- The largest integer ≤ 4.7 is 4.
- So, Floor(4.7) = 4.
Example 2: Floor of -3.2
- The largest integer ≤ -3.2 is -4.
- So, Floor(-3.2) = -4.
Key Observation:
For positive numbers, the floor is just the integer part.
For negative numbers, the floor is the next negative integer below the current number.
For example, imagine you have 17 apples, and each basket can hold 5 apples.
You want to know how many full baskets you can fill — without leaving any basket half-full.
So you do the division:
17 ÷ 5 = 3.4
But you can’t have 0.4 of a basket, right? So you only count the full ones.
That’s where the floor comes in:
Floor(3.4) = 3
So, you can fill 3 full baskets.
What is Ceil?
Awesome! Let’s keep using the building idea — it’s a super simple way to understand things.
So, imagine you're in a building with storeys: ground storey (0), 1st storey, 2nd storey, 3rd storey, and so on. And let’s say each storey is 1.0 height tall — like from 3.0 to 4.0 is the 4th storey.
Now, imagine you’re climbing the stairs and you stop at height 3.7. That means you’ve already passed the 3rd storey, but you’re not at the 4th storey yet. Now, if someone asks you, “What’s the next storey you’ll reach if you go up just a little more?” — the answer is: storey 4.
That’s what ceil (or ceiling) means in math. It’s like the next full storey above you.
The ceil of a number is the smallest integer that is equal to or greater than that number.
So:
- At 3.7, the ceil is 4 — the next storey above you.
- If you're at 2.1, you're between storey 2 and 3, so ceil is 3.
- If you're at 4.9, you're almost at 5, and ceil is 5.
- If you’re standing exactly at 6.0, then you’re already on a full storey, so the ceil is 6.
Now let’s think about going underground — like moving up from the basement floors to the ground floor.
If you’re at -1.4, you’re between basement storey -2 and -1. The very next full storey above you is -1, so the ceil of -1.4 is -1.
So, just like a ceiling in a room is the next surface above your head, the ceil of any number is the next full storey you’ll reach if you take even the tiniest step upward — unless you're already standing on it!

Example 1: Ceil of 4.3
- The smallest integer ≥ 4.3 is 5.
- So, Ceil(4.3) = 5.
Example 2: Ceil of -2.8
- The smallest integer ≥ -2.8 is -2.
- So, Ceil(-2.8) = -2.
Key Observation:
For positive numbers, the ceil rounds up to the next integer if there’s a decimal part.
For negative numbers, the ceil is just the integer part.
For example, suppose you have 17 people, and each car can hold 5 people.
You want to know how many cars you need so that everyone fits — no one should be left out.
So you divide:
17 ÷ 5 = 3.4
But you can’t have 0.4 of a car, right? You need a whole car for the extra people.
That’s where ceil helps:
Ceil(3.4) = 4
So, you’ll need 4 cars to fit all 17 people.
In short:
- Floor is like asking: “What’s the last floor I passed?”
- Ceil is like asking: “What’s the next full floor I’ll reach?”
Both help you figure out where you are in the number-building!
These concepts are widely used in binary search and mathematics.
How to find Ceil and Floor Algorithm
Now that we understand what Floor and Ceil are, let's derive their mathematical formulas and learn how to calculate them.
1. How to Calculate Floor Mathematically?
The Floor of a number x, denoted as ⌊x⌋, is the largest integer that is less than or equal to x.
- If x is already an integer, then Floor(x) = x.
- If x is positive and has decimals, we remove the decimal part to get the integer.
- If x is negative and has decimals, we move to the next lower integer.
For Positive Numbers (x ≥ 0)
If x is positive, the simplest way is to remove the decimal part and convert it to an integer.
For example:
- 4.7 → 4
- 9.3 → 9
- 5.0 → 5 (already an integer)
Thus, for positive numbers, we can simply take int(x), because converting a positive decimal number to an integer automatically removes the fractional part.
Floor(x) = int(x)
For Negative Numbers (x < 0)
Negative numbers behave differently. If x is negative, just removing the decimal part does not always give the Floor.
Let’s say you have a number like -2.7. If you just remove the decimal part, you get -2.
But that’s not the floor — because -2 is actually above -2.7.
Remember, the floor means going down to the next lower integer. So for -2.7, the floor is -3, not -2. You have to go one step lower.
We need to go down to the next integer below x. That means subtracting 1 from x’s integer part, but only if x isn’t already an integer.
So, for negative numbers:
Floor(x) = int(x) − 1 ,if x ≠ int(x)
Example Calculation:
- Floor(-3.2) = int(-3.2) - 1 = -4
- Floor(-5.7) = int(-5.7) - 1 = -6
- Floor(-7.0) = int(-7.0) = -7 (No change needed because -7 is already an integer)
Final Formula for Floor
Now, we can summarize:
Floor(x) = int(x), if x ≥ 0
Floor(x) = int(x) - 1, if x < 0 and x ≠ int(x)
2. How to Calculate Ceil Mathematically?
The Ceil of a number x, denoted as ⌈x⌉, is the smallest integer that is greater than or equal to x.
- If x is already an integer, then Ceil(x) = x.
- If x is positive and has decimals, we move to the next integer above x.
- If x is negative, we remove the decimal part.
For Positive Numbers (x ≥ 0)
If you have a number like 4.3, the next integer is 5.
If it’s 7.6, the next integer is 8.
But if it’s already a integer like 2.0, then you’re already there — so the answer is just 2.
So here's an easy rule:
1. If the number has decimals, just go up to the next integer.
2. If it’s already a integer, just keep it the same.
We can write it like this:
Ceil(x) = int(x) + 1, if x is not already an integer.
Ceil(x) = x, if x is an integer
For example:
- 4.7 → 5
- 9.3 → 10
- 5.0 → 5 (already an integer)
It’s like climbing stairs — if you're already on a full storey, stay there.
But if you’re in between, go up to the next one!
For Negative Numbers (x < 0)
For negative integers, the simplest way is to remove the decimal part by converting it to an integer.
So, for negative numbers:
Ceil(x) = int(x)
Example Calculation:
- Ceil(-2.8) = int(-2.8) = -2
- Ceil(-5.3) = int(-5.3) = -5
- Ceil(-7.0) = int(-7.0) = -7 (No change needed because -7 is already an integer)
Final Formula for Ceil
Now, we can summarize:
Ceil(x) = int(x) + 1, if x ≥ 0 and x ≠ int(x)
Ceil(x) = int(x), if x < 0
How to code it up:
Define customFloor(x)
- If x is non-negative, return int(x).
- If x is negative, check:
- If x is already an integer, return int(x).
- Otherwise, subtract 1 from int(x).
Define customCeil(x)
- If x is negative, return int(x).
- If x is non-negative, check:
- If x is already an integer, return int(x).
- Otherwise, add 1 to int(x).
Main program
- Take user input as a floating-point number.
- Call the customFloor(x) and customCeil(x) functions.
- Print the results.
How to find Ceil and Floor Solution
Code Implementation
1. How to find Ceil and Floor Solution C++ Try on Compiler
#include <iostream>
using namespace std;
// Function to compute Floor using if-else
int customFloor(double x) {
if (x >= 0) {
return int(x);
} else {
if (x == int(x)) {
return x;
} else {
return int(x) - 1;
}
}
}
// Function to compute Ceil using if-else
int customCeil(double x) {
if (x < 0) {
return int(x);
} else {
if (x == int(x)) {
return x;
} else {
return int(x) + 1;
}
}
}
int main() {
double x;
cout << "Enter a number: ";
cin >> x;
cout << "Floor(" << x << ") = " << customFloor(x) << endl;
cout << "Ceil(" << x << ") = " << customCeil(x) << endl;
return 0;
}
2. How to find Ceil and Floor Solution Java Try on Compiler
import java.util.Scanner;
public class FloorCeilCalculator {
// Function to compute Floor using if-else
public static int customFloor(double x) {
if (x >= 0) {
return (int) x;
} else {
if (x == (int) x) {
return x;
} else {
return (int) x - 1;
}
}
}
// Function to compute Ceil using if-else
public static int customCeil(double x) {
if (x < 0) {
return (int) x;
} else {
if (x == (int) x) {
return x;
} else {
return (int) x + 1;
}
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
double x = scanner.nextDouble();
scanner.close();
System.out.println("Floor(" + x + ") = " + customFloor(x));
System.out.println("Ceil(" + x + ") = " + customCeil(x));
}
}
3. How to find Ceil and Floor Solution Python Try on Compiler
def custom_floor(x):
if x >= 0:
return int(x)
else:
if x == int(x):
return x
else:
return int(x) - 1
def custom_ceil(x):
if x < 0:
return int(x)
else:
if x == int(x):
return x
else:
return int(x) + 1
# Taking user input
x = float(input("Enter a number: "))
print(f"Floor({x}) = {custom_floor(x)}")
print(f"Ceil({x}) = {custom_ceil(x)}")
4. How to find Ceil and Floor Solution Javascript Try on Compiler
function customFloor(x) {
if (x >= 0) {
return Math.floor(x);
} else {
if (x === Math.floor(x)) {
return x;
} else {
return Math.floor(x) - 1;
}
}
}
function customCeil(x) {
if (x < 0) {
return Math.floor(x);
} else {
if (x === Math.floor(x)) {
return x;
} else {
return Math.floor(x) + 1;
}
}
}
// Taking user input in a browser or Node.js
const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout
});
readline.question("Enter a number: ", (x) => {
x = parseFloat(x);
console.log(`Floor(${x}) = ${customFloor(x)}`);
console.log(`Ceil(${x}) = ${customCeil(x)}`);
readline.close();
});
Complexity Analysis for How to find Ceil and Floor Solution
Time Complexity: O(1)
Both customFloor(x) and customCeil(x) follow a constant time complexity (O(1)) because they execute a fixed number of operations irrespective of the input value.
1. Analyzing customFloor(x)
Function customFloor(x):
- If x is greater than or equal to 0, return int(x), which takes O(1).
- Else:
- If x is already an integer, return int(x), which takes O(1).
- Otherwise, return int(x) - 1, which also takes O(1).
Each condition is checked only once, and at most one subtraction operation is performed.
No loops or recursion are used.
Time Complexity: O(1) (Constant Time).
2. Analyzing customCeil(x)
Function customCeil(x):
- If x is less than 0, return int(x), which takes O(1).
- Else:
- If x is already an integer, return int(x), which takes O(1).
- Otherwise, return int(x) + 1, which also takes O(1).
Similar to customFloor(x), each condition runs in constant time.
The maximum number of operations performed is one addition.
No loops or recursion are involved.
Time Complexity: O(1) (Constant Time).
3. Overall Complexity
Since both functions operate in constant time, the overall complexity of computing Floor and Ceil for any given number is:
O(1) + O(1) = O(1).
The entire program, including input/output operations, also runs in O(1) time.
Space Complexity: O(1)
Auxiliary Space Complexity: O(1 )
Explanation: We are only using a few integer variables—such as int(x) (to store the integer part of x) and an additional variable (for adjustments in floor and ceil calculations). No additional data structures like arrays, lists, or hash maps are used.
Thus, the auxiliary space complexity is O(1) since only a constant amount of extra space is required.
Total Space Complexity: O(1)
Explanation: Unlike problems involving arrays or lists, our algorithm only takes a single floating-point input (x). Since we do not use any additional data structures, the total space used remains constant.
Thus, the total space complexity is O(1).
Built-in Floor and Ceil Functions
Most programming languages provide built-in functions to compute Floor(x) and Ceil(x) efficiently. These functions are highly optimized and eliminate the need for manual implementation.
Built-in Floor and Ceil Functions in Different Languages
- C++ (cmath library)
C++ provides std::floor() and std::ceil() from the <cmath> library. - Java (Math class)
Java provides Math.floor() and Math.ceil() in the Math class. - Python (math module)
Python provides math.floor() and math.ceil() in the math module. - JavaScript (Math Object)
JavaScript provides Math.floor() and Math.ceil() in the Math object.
How to find Ceil and Floor Solution
Code Implementation
1. How to find Ceil and Floor Solution C++ Try on Compiler
#include <iostream>
#include <cmath> // For floor() and ceil()
using namespace std;
int main() {
double x;
cout << "Enter a number: ";
cin >> x;
cout << "Floor: " << floor(x) << endl;
cout << "Ceil: " << ceil(x) << endl;
return 0;
}
2. How to find Ceil and Floor Solution Java Try on Compiler
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
double x = scanner.nextDouble();
System.out.println("Floor: " + Math.floor(x));
System.out.println("Ceil: " + Math.ceil(x));
scanner.close();
}
}
3. How to find Ceil and Floor Solution Python Try on Compiler
import math
x = float(input("Enter a number: "))
print("Floor:", math.floor(x))
print("Ceil:", math.ceil(x))
4. How to find Ceil and Floor Solution Javascript Try on Compiler
// Input from user
const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout
});
readline.question("Enter a number: ", input => {
let x = parseFloat(input);
console.log("Floor:", Math.floor(x));
console.log("Ceil:", Math.ceil(x));
readline.close();
});
Complexity Analysis for How to find Ceil and Floor Solution
Time Complexity: O(1)
- The built-in floor() and ceil() functions involve only a few arithmetic operations and conditional checks.
- They extract the integer part of a number and make a simple adjustment (if necessary), which runs in constant time.
- Since these functions operate with a constant number of steps, the time complexity remains O(1).
Space Complexity: O(1)
Auxiliary Space Complexity: O(1 )
Explanation: The function only uses a few integer/float variables for storing floor(x) and ceil(x). No additional data structures like arrays, lists, or hash maps are used.
Since the extra memory required is constant, the auxiliary space complexity is O(1).
Total Space Complexity: O(1)
Explanation: The function takes only one input (x) and does not use any additional memory beyond a few variables.
Unlike recursive implementations, which may require O(log x) stack space, the built-in functions work iteratively in constant space.
Thus, the total space complexity remains O(1).
Ceil of a Division in Competitive Programming
Alright, let’s walk back into our building for a second.
Say you’re trying to divide people into rooms on each floor. You’ve got x people, and each floor can hold y people. The question is: how many full floors do we need to fit everyone?
Now in programming, especially competitive programming where performance matters, you often need to figure out how many groups something splits into — like pages of results, chunks of work, or even how many buses are needed for people.
Normal Division Gives You the Floor
Let’s start with normal integer division.
Suppose you write:
x / y (using integer division)
That gives you the floor value — basically, it tells you how many full floors you can fill with y people per floor.
Example:
If x = 10 and y = 3, then:
10 / 3 = 3 (floor division)
You’re filling 3 full floors, and 1 person is left out — but that person still needs a place! So we actually need 4 floors to fit everyone.
When You Want the Ceil Value
You’re now asking:
“How many full floors do I need to cover all x people?” — even if the last one isn't completely full.
This is the ceiling of x / y.
In normal math, you’d write:
ceil(x / y)
Intuition Behind the Trick Formula
In competitive programming, we want to avoid using floating-point division and actual ceil functions (they're slower or not allowed in integer-only environments).
So here's the magic trick:
ceil(x / y) = (x + y - 1) / y
And yes, this works with integer division.
Why Does This Work?
Imagine you’re "pushing" the remainder just enough so that it tips over to the next floor.
Let’s go back to our example:
x = 10, y = 3
Now, instead of doing 10 / 3, we do:
(10 + 3 - 1) / 3 = 12 / 3 = 4
Boom — we got the ceil of 10 ÷ 3.
Why did we add (y - 1) to x?
Because we’re kind of “rounding up” artificially.
If there’s any remainder in the division, adding (y - 1) pushes it over the edge to the next integer.
Let’s break it into two cases:
Case 1: When x is perfectly divisible by y
Say x = 12, y = 4
- Regular division: 12 / 4 = 3
- Our trick: (12 + 4 - 1) / 4 = (15) / 4 = 3 (since 15 // 4 is 3)
So it gives us the correct result.
Case 2: When x is not perfectly divisible by y
Say x = 13, y = 4
- Regular division: 13 / 4 = 3 → floor
- Ceil should be 4
- Trick formula: (13 + 4 - 1) / 4 = 16 / 4 = 4
Perfect!
Proof Using Math:
We know:
- x / y gives floor division
- floor(x / y) ≤ x / y < floor(x / y) + 1
So we want the smallest integer n such that:
n ≥ x / y
Which means:
n * y ≥ x
Now flip that: to get n, you want:
n = ceil(x / y) = the smallest n such that n * y ≥ x
If you try:
(x + y - 1) / y, this guarantees:
- If x is divisible by y → it gives exact result
- If x leaves a remainder → the added (y - 1) ensures it bumps up to the next integer
Why? Because:
x + y - 1 ensures any remainder is "pushed up" enough so when you divide, the integer division gives you the ceiling.
Summary
- Normal integer division x / y gives floor(x / y)
- If you want ceil(x / y) in pure integer math, use: (x + y - 1) / y
Real-World Examples of Floor and Ceil Functions
Floor and Ceil functions are widely used in real-life scenarios, especially in situations where rounding values is necessary. Here are some practical examples:
1. Ticket Pricing in Public Transport
- Suppose bus fare is $2.50 per mile, but passengers cannot be charged fractions of a dollar.
- If a person travels 3.6 miles, the fare must be rounded using ceil (rounding up) to $4.00.
- If there is a discount where users pay only for full miles traveled, the fare uses floor (rounding down) to $3.00.
2. Packing Items into Boxes (Logistics and Warehousing)
- A company needs to pack 27 items into boxes, with each box holding 5 items.
- Ceil(27/5) = 6, so 6 boxes are needed.
- Floor(27/5) = 5, meaning only 5 boxes will be completely full.
3. Flooring and Tiling in Construction
- A room of 12.7 square meters requires 1 square meter tiles.
- Ceil(12.7) = 13, meaning 13 tiles are needed.
- If we count only the completely covered area, we use Floor(12.7) = 12 tiles.
4. Salary and Tax Calculations
- Some tax brackets use ceilings:
- A person earning $42,450 falls into a tax bracket where the threshold is $40,000.
- Tax is applied to Ceil(42,450/1000) * 1000 = $43,000.
5. Finding Floor and Ceil in a Sorted Array (Search Optimization)
- Application in Databases and Search Engines:
- Suppose an online store sorts items by price, and a customer searches for a budget of $55.
- The store has sorted prices: [10, 25, 40, 60, 75, 100].
- The closest match below $55 (floor) is 40.
- The closest match above $55 (ceil) is 60.
- The store suggests items accordingly.
Similar Questions
Now, let's try similar problems
In a special ranking system, each voter gives a rank from highest to lowest to all teams participating in the competition.
The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie again, we continue this process until the ties are resolved. If two or more teams are still tied after considering all positions, we rank them alphabetically based on their team letter.
You are given an array of strings votes which is the votes of all voters in the ranking systems. Sort all teams according to the ranking system described above.
Return a string of all teams sorted by the ranking system.