The first and the last terms of an AP are 5 and 45 respectively. If the sum of all its terms is 40, find the common difference and the number of terms.