The ratio of the number of Sam's books to Charlie's was 4:9 at first. Then, Sam bought 30 more books while Charlie gave away 15 books. In the end, the ratio of the number of Sam's books to Charlie's books was 5:3. How many books did Sam have at first?

Let's start by setting up some equations to represent the given information.

Let S be the number of books Sam had at first, and let C be the number of books Charlie had at first. We know that:

S:C = 4:9

This means that Sam had 4x books and Charlie had 9x books, for some value of x.

After Sam bought 30 books, he had 4x + 30 books. And after Charlie gave away 15 books, he had 9x - 15 books. The ratio of Sam's books to Charlie's books at this point was:

(4x + 30):(9x - 15)

We're told that this ratio is 5:3, so we can set up another equation:

(4x + 30):(9x - 15) = 5:3

To solve for x, we can cross-multiply:

3(4x + 30) = 5(9x - 15)

Simplifying:

12x + 90 = 45x - 75

Subtracting 12x and adding 75 to both sides:

165 = 33x

x = 5

So at first, Sam had 4x books, or 4(5) = 20 books.

Let's denote the number of books Sam had initially as "x" and the number of books Charlie had initially as "y".

According to the information given, at first, the ratio of the number of Sam's books to Charlie's books was 4:9, which can be written as:

x/y = 4/9

After Sam bought 30 more books, the number of Sam's books increased to x + 30.

Similarly, after Charlie gave away 15 books, the number of Charlie's books decreased to y - 15.

Now, we are given that the ratio of the number of Sam's books to Charlie's books in the end was 5:3, which can be written as:

(x + 30) / (y - 15) = 5/3

Simplifying this equation, we get:

3(x + 30) = 5(y - 15)

3x + 90 = 5y - 75

3x - 5y = -165 ...........(1)

We can solve the equations (1) and (4) simultaneously to find the values of x and y, and then determine the initial number of books Sam had (x).

Let's solve the equations (1) and (2):

x/y = 4/9 ...........(2)

Rearranging equation (2), we have:

x = (4/9)y ...........(3)

Substituting equation (3) into equation (1):

3(4/9)y - 5y = -165

(12/9)y - 5y = -165

(12 - 45/9)y = -165

(12 - 45)y/9 = -165

(12 - 45)y = -165 * 9

-33y = -1485

y = -1485 / -33

y = 45

Substituting the value of y into equation (3):

x = (4/9)(45)

x = 20

Therefore, Sam initially had 20 books.