views:

191

answers:

4

I have some code where, if a user has referred X number of people, he will get X number of credits.

For example, referring 2 people = 1 credit. 4 people = 2 credits, and so on.

However where this gets tricky is, the numbers can be changed so he gets 1 credit per person, or 1 credit per 3 people, 1 credit for 5 people, etc.

If he gets 1 credits for 3 people, and he has referred 5 people, then I would like him to receive 1 credit, and have it stored that he still has 2 people for whom he didn't get any credits. So the next time he refers someone, it is 2 + 1 = 3, and he gets a credit.

My question is,

Given X = Number of people he needs to refer for 1 credit, and Y = Number of people a user has refered,

(So X might be 3, as in 3 people per credit, and Y might be 6, in which case he should get 2 credits)

1) What's a straightforward formula or function which will X and Y, and return the number of credits which should be given to that person, and

2) Which will also give a remainder for the credits which can't be awarded yet. E.g if X is 3 and Y is 5, the credits would be 1, and remainder would be 2, so with the next referer Y will become 3 again and the user would get 1 credit?

+9  A: 
1.) 
creditsToPayout = Y/X; //use integer division to truncate, or floor result
remainderReferrals = Y % X; //remainder of Y / X, leftover referrals
Stefan Kendall
A: 

Number of credits = FLOOR(Y/X)

Remainder = Y-(X*FLOOR(Y/X))

Ruffles
+1  A: 

You need integer division and modulus. For PHP see here for :

 - intval($a / $b)
 - $a % $b
van
+1  A: 

If the number can change over time, what happens if, say, intially it is 3 people per credit. He refers 7 people and gets 2 credits with 1 person left over. Then the rule is changed to 4 people per credit. Under that rule he would only get 1 credit with 3 people left over. Do you take a credit back? I'm guessing not, that the new rule only applies to new credits. So I think you need to keep on your database or whatever, the number of credits received, and the number of referrals left that was not sufficient to make a credit. The number of un-credited referrals would then go up and down over time, as he makes new referrals and as they are "exchanged" for credits.

Frankly I think it would be simpler if you could make the rule be X credits per referral rather than X referrals per credit, and then just increase the cost of whatever it is you buy with the credits. Like, if the rule is 1 credit for 5 referrals, and when you get 10 credits you get a free iPod or whatever, then you need 50 referrals to get an iPod. So change it to 1 credit per referral and it takes 50 credits to get an iPod. Then you'd never have to deal with the fractions. But maybe you're not making up the rules and this is all irrelevant.

Jay