Is there a universal formula for how you could work this out?
This is a part of a coding problem I’m attempting to solve and simple solutions like going through each integer and checking if it contains the number 9 is way too slow.
closest I’ve got so far (working in c#) is this:
using System;
using System.Numerics;
public static class Kata {
public static BigInteger Nines(BigInteger n)
{
BigInteger a = 0;
for (BigInteger i = 0; i < BigInteger.Parse((Math.Floor(Math.Log10((double)n))+1).ToString()); i++)
{
long c = (long)((Math.Floor((double)n /Math.Pow(10,(double)i)) % 10));
a = c < 9 ? (long)(((double)c*(Math.Pow(9,(double)i))) + (double)a) : (long)(c*(Math.Pow(9,(double)i)));
}
return n-a;
}
}
however I noticed that when n=3950 for example, I begin getting incorrect values (for this specific case the function returns 1034 instead of 1035 and I’m not sure where I’ve gone wrong. The error gets even bigger for larger values of n)
konrad is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.