Year to Century Function

Viewed 30952

Problem: Given a year, return the century it is in. The first century spans from the year 1 up to and including the year 100, the second - from the year 101 up to and including the year 200, etc.

My Code:

def centuryFromYear(year):
    century = year/100 
    decimal = int(str(century[-2:-1]))
    integer = int(str(century)[:2])

    if decimal > 0:
        return integer + 1
    else:
        return integer

print(centuryFromYear(2017))

This doesn't seem to work in certain cases. like when year = 2001 or year = 2000.

Would anyone be able to provide a more simple piece of code?

14 Answers

You can use integer division, operator // in python 3:

def centuryFromYear(year):
    return (year) // 100 + 1    # 1 because 2017 is 21st century, and 1989 = 20th century

print(centuryFromYear(2017))  # --> 21

Please note: This does not account for century BC, and it uses a cut off date at Dec 31st xy99 where it is sometimes strictly defined as Dec 31st xy00
more info here

if you wanted to set the cutoff on Dec 31st xy00, which is more strict, you would likely want to do like this:

def centuryFromYear(year):
    return (year - 1) // 100 + 1    # 1 because 2017 is 21st century, and 1989 = 20th century

print(centuryFromYear(2017))  # --> 21
  • Python simple one-liner Solution & JavaScript one-liner Solution

  • Use inbuilt Math functions in javascript for one-line answer

  • Math.ceil function always rounds a number up to the next largest whole number or integer.

// Python one-liner solution

def centuryFromYear(year):
    return (year + 99) // 100

// Javascript one-liner solution

function centuryFromYear(year) {

    return Math.ceil(year/100)

}

You can use the ceiling function available in 'math' module to get the desired solution.

def centuryFromYear(year):
 return math.ceil(year/100) 

With integer division, works properly both for 2000 and for 2017:

1 + (year - 1) // 100  

Another alternative which works for 0-9999 which is more in the lines of your attempts.

year = 2018
cent = int(str(year).zfill(4)[:2])+1
print(cent)

Returns:

21
def centuryFromYear(year):
    return -(-year // 100)

its rather old, but this is the correct century output. its a negative floor division

1700 // 100 = 17 1701 // 100 = 17 - (-1701 // 100) = 18

it makes the floor division on -1701//100 which is -18

works for all years and is 1 line only

First start by subtracting 1 from the year in context

def centuryFromYear(year):
    return (year - 1) // 100 + 1

Works for implementing the following examples:

print(centuryFromYear(2000))  # --> 20
print(centuryFromYear(2001))  # --> 21
print(centuryFromYear(2017))  # --> 21

THIS WORKED FOR ME:

def whatCenturyIsX(x):

    #turn our input into a string for modification
    x = str(x)
    #separate the characters of x into a list for further use
    xlist = list(x)
    #set a boolean to contatin negativity or positivity of the number
    #if the "minus" sign is in x, set the boolean to true and remove the "minus" for easier handling of the variable
    #(the minus doesn't tell us anything anymore because we already set the boolean)
    negative = False
    if "-" in xlist:
        negative = True
        xlist.remove("-")
        for i in xlist:
            x += i

    #to define what century year x is in, we are going to take the approach of adding 1 to the first n characters, when N is the number of digits - 2. This is proved. So:
    
    #also, we need the string to be at least 4 characters, so we add 0's if there are less

    if len(xlist) >= 4:
        pass
        
    
    else:
        if len(xlist) == 3:
            xlist.insert(0, 0)
            x = ""
            for i in xlist:
                x += str(i)
        elif len(xlist) == 2:
            xlist.insert(0, 0)
            xlist.insert(1, 0)
            x = ""
            for i in xlist:
                x += str(i)
        elif len(xlist) == 1:
            
            xlist.insert(0, 0)
            xlist.insert(1, 0)
            xlist.insert(2, 0)
            x = ""
            for i in xlist:
                x += str(i)
        

    n = len(xlist) - 2
    #j is the number formed by the first n characters.
    j = ""
    for k in range(0, n):
        #add the first n characters to j
        j += str(xlist[k])
        #finally form the century by adding 1 to j and calling it c.
    c = int(j) + 1



    #for the final return statement, we add a "-" and "B.C." if negative is true, and "A.C." if negative is false.
    if negative:
        xlist.insert(0, "-")
        x = ""
        for i in xlist:
            x += str(i)
        return(str(x) + " is en the century " + str(c) + " B.C.")
    else:
        return(str(x) + " is en the century " + str(c) + " A.C.")

I solved this problem in PHP.

function centuryFromYear($year) {
    if ($year % 100 == 0){
        return $year/100;
    }
    else {
        return ceil($year/100);
    }
}

Note :-

  1. The ceil() function rounds a number UP to the nearest integer.
  2. To round a number DOWN to the nearest integer, look at the floor() function.
  3. To round a floating-point number, look at the round() function.
def solution(year):
    if (year % 100) == 0:
        return (year) // 100
    else:
        return (year) // 100 + 1
year= int(input())
century = (year - 1) // 100 + 1
print(century)

I actually have one of the most elegant codes for this and I will share the C version with you.

#include<math.h>
#include<stdio.h>

int main() {
  float x;
  int y;

  fscanf(stdin, "%f", &x);
  x = x / 100;
  y = ceil(x);

  fprintf(stdout, "Century %d ", y);

  return 0;
}

This is the correct answer:

def centuryFromYear(year):
  if year % 100 == 0:
    return year // 100 
  else:
    return year // 100 + 1
Related