I have the following pattern. I want to express 'a' as a function of n.
if n=0 then a=0
if n=1 then a=0
if n=2 then a=3
if n=3 then a=3
if n=4 then a=10
.
.
.
if n=10 then a=10
if n=11 then a=29
.
.
.
if n=29 then a=29
if n=30 then a=66
.
.
.
if n=66 then a=66
if n=67 then a=127
.
.
AS you can see the value of a
remains the same till a
value matches with n
. After which the value of a
changes and again this value holds till a<=n
. I found the formula with which this pattern occurrs. It is
a = 1^3 + 2
when n<=3
a = 2^3 + 2
when n > 3 and n <=10
and so on.
How to express a
as a function of n
?
like f(n) = {___ <condition>
You can apply the inverse of the formula n^3-2
, round up, and then apply the formula again, to get the correct sequence. The values for 0, 1 and 2 have to be hard-coded, though.
Note: in languages with typed numbers, make sure the result of the cubic root is a float; if it is converted to int automatically, it will be rounded down in the conversion.
function calculate(n) {
if (n <= 1) return 0;
if (n == 2) return 3;
return Math.pow(Math.ceil(Math.pow(n - 2, 1 / 3)), 3) + 2;
}
for (var i = 0; i < 70; i++) {
document.write(i + "→" + calculate(i) + " ; ");
}
Addendum: as Stefan Mondelaers commented, you have to be careful when relying on floating point maths. The code above makes use of the fact that cubic roots of third powers are always slightly underestimated in JavaScript (at least in all current browsers I tested); e.g. the largest third power within JavaScript's safe integer range is 4,503,569,204,744,000 but instead of its cubic root 165,140 you will get:
document.write(Math.pow(4503569204744000, 1/3));
If you're going to round off the results of floating point calculations, these very small errors may lead to bigger errors. The simplest work-around is indeed to add or subtract a very small value before rounding. For more information see e.g. this question.