How to calculate the infinite value of a division? [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to know the repeating decimal in a fraction?
1/3 is different by 3/10. 0.33333 != 0.3
So 1/3 will be 0.3 (with a line above number three)
1/12 = 0.833333 = 0.083 (with a line above number three)
1/13 = 0.076923076923 = 0.|076923|
Those lines represent the repeating part.
I plan to have this model in a class. I'm a bit lost on this situation. I just need some ideas to know determine the repeating value. Thanks.

Cycle detection algorithm is the answer. You can use Floyd's cycle detection algorithm or Brent's cycle detection algorithm.
The function to plug into those algorithms is the function to produce the next digit of the quotient.

At each step, divide, floor, take the remainder, multiply that by ten, repeat until you get the same number.
For example, for 1/81:
1/81 = 0 with remainder 1 0
10/81 = 0 with remainder 10 0.0
100/81 = 1 with remainder 19 0.01
190/81 = 2 with remainder 28 0.012
280/81 = 3 with remainder 37 0.0123
...
10/81 = 0 with remainder 10; saw this already.
0.|012345679|
Here's a sample implementation:
private static string GetRepeatingPart(int n, int d) {
var seen = new HashSet<int>();
var result = new StringBuilder();
n = (n % d) * 10;
while(true) {
int p = n / d;
n = (n % d) * 10;
if(seen.Contains(n)) {
return result.ToString();
}
result.Append(p);
seen.Add(n);
}
}

Related

multiplicative persistence - recursion?

I'm working on this:
Write a function, persistence, that takes in a positive parameter num
and returns its multiplicative persistence, which is the number of
times you must multiply the digits in num until you reach a single
digit.
For example:
persistence(39) == 3 // because 3*9 = 27, 2*7 = 14, 1*4=4
// and 4 has only one digit
persistence(999) == 4 // because 9*9*9 = 729, 7*2*9 = 126,
// 1*2*6 = 12, and finally 1*2 = 2
persistence(4) == 0 // because 4 is already a one-digit number
This is what I tried:
public static int Persistence(long n)
{
List<long> listofints = new List<long>();
while (n > 0)
{
listofints.Add(n % 10);
n /= 10;
}
listofints.Reverse();
// list of a splited number
int[] arr = new int[listofints.Count];
for (int i = 0; i < listofints.Count; i++)
{
arr[i] = (int)listofints[i];
}
//list to array
int pro = 1;
for (int i = 0; i < arr.Length; i++)
{
pro *= arr[i];
}
// multiply each number
return pro;
}
I have a problem with understanding recursion - probably there is a place to use it. Can some1 give me advice not a solution, how to deal with that?
It looks like you've got the complete function to process one iteration. Now all you need to do is add the recursion. At the end of the function call Persistence again with the result of the first iteration as the parameter.
Persistence(pro);
This will recursively call your function passing the result of each iteration as the parameter to the next iteration.
Finally, you need to add some code to determine when you should stop the recursion, so you only want to call Persistence(pro) if your condition is true. This way, when your condition becomes false you'll stop the recursion.
if (some stop condition is true)
{
Persistence(pro);
}
Let me take a stab at explaining when you should consider using a recursive method.
Example of Factorial: Factorial of n is found by multiplying 1*2*3*4*..*n.
Suppose you want to find out what the factorial of a number is. For finding the answer, you can write a foreach loop that keeys multiplying a number with the next number and the next number until it reaches 0. Once you reach 0, you are done, you'll return your result.
Instead of using loops, you can use Recursion because the process at "each" step is the same. Multiply the first number with the result of the next, result of the next is found by multiplying that next number with the result of the next and so on.
5 * (result of rest)
4 * (result of rest )
3 * (result of rest)
...
1 (factorial of 0 is 1).---> Last Statement.
In this case, if we are doing recursion, we have a terminator of the sequence, the last statement where we know for a fact that factorial of 0 = 1. So, we can write this like,
FactorialOf(5) = return 5 * FactorialOf(4) = 120 (5 * 24)
FactorialOf(4) = return 4 * FactorialOf(3) = 24 (4 * 6)
FactorialOf(3) = return 3 * FactorialOf(2) = 6 (3 * 2)
FactorialOf(2) = return 2 * FactorialOf(1) = 2 (2 * 1)
FactorialOf(1) = return 1 * FactorialOf(0) = 1 (1 * 1)
FactorialOf(0) = Known -> 1.
So, it would make sense to use the same method over and over and once we get to our terminator, we stop and start going back up the tree. Each statement that called the FactorialOf would start returning numbers until it reaches all the way to the top. At the top, we will have our answer.
Your case of Persistence
It calls for recursive method as well as you are taking the result and doing the same process on it each time.
Persistence(39) (not single) = return 1 + Persistence(3 * 9 = 27) = 3
Persistence(27) (not single) = return 1 + Persistence(2 * 7 = 14) = 2
Persistence(14) (not single) = return 1 + Persistence(1 * 4 = 4) = 1
Persistence(4) (single digit) = Known -> 0 // Terminator.
At the end of the day, if you have same process performed after each calculation / processing with a termination, you can most likely find a way to use recursion for that process.
You definitely can invoke your multiplication call recursively.
You will need initial sate (0 multiplications) and keep calling your method until you reach your stop condition. Then you return the last iteration you've got up to as your result and pass it through all the way up:
int persistence(int input, int count = 0) {} // this is how I would define the method
// and this is how I see the control flowing
var result = persistence(input: 39, count: 0) {
//write a code that derives 27 out of 39
//then keep calling persistence() again, incrementing the iteration count with each invocation
return persistence(input: 27, count: 1) {
return persistence(input: 14, count: 2) {
return persistence(input: 4, count: 3) {
return 3
}
}
}
}
the above is obviously not a real code, but I'm hoping that illustrates the point well enough for you to explore it further
Designing a simple recursive solution usually involves two steps:
- Identify the trivial base case to which you can calculate the answer easily.
- Figure out how to turn a complex case to a simpler one, in a way that quickly approaches the base case.
In your problem:
- Any single-digit number has a simple solution, which is persistence = 1.
- Multiplying all digits of a number produces a smaller number, and we know that the persistence of the bigger number is greater than the persistence of the smaller number by exactly one.
That should bring you to your solution. All you need to do is understand the above and write that in C#. There are only a few modifications that you need to make in your existing code. I won't give you a ready solution as that kinda defeats the purpose of the exercise, doesn't it. If you encounter technical problems with codifying your solution into C#, you're welcome to ask another question.
public int PerRec(int n)
{
string numS = n.ToString();
if(numS.Length == 1)
return 0;
var number = numS.ToArray().Select(x => int.Parse(x.ToString())).Aggregate((a,b) => a*b);
return PerRec(number) + 1;
}
For every recursion, you should have a stop condition(a single digit in this case).
The idea here is taking your input and convert it to string to calculate that length. If it is 1 then you return 0
Then you need to do your transformation. Take all the digits from the string representation(in this case from the char array, parse all of them, after getting the IEnumerable<int>, multiply each digit to calculate the next parameter for your recursion call.
The final result is the new recursion call + 1 (which represents the previous transformation)
You can do this step in different ways:
var number = numS.ToArray().Select(x => int.Parse(x.ToString())).Aggregate((a,b) => a*b);
convert numS into an array of char calling ToArray()
iterate over the collection and convert each char into its integer representation and save it into an array or a list
iterate over the int list multiplying all the digits to have the next number for your recursion
Hope this helps
public static int Persistence(long n)
{
if (n < 10) // handle the trivial cases - stop condition
{
return 0;
}
long pro = 1; // int may not be big enough, use long instead
while (n > 0) // simplify the problem by one level
{
pro *= n % 10;
n /= 10;
}
return 1 + Persistence(pro); // 1 = one level solved, call the same function for the rest
}
It is the classic recursion usage. You handle the basic cases, simplify the problem by one level and then use the same function again - that is the recursion.
You can rewrite the recursion into loops if you wish, you always can.

c# going through an int and adding every character to a sum [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
while (sum != 0)
{
n += sum % 10;
sum /= 10;
}
I know what the code does, but can someone explain me how it works?
% 10 returns the modulo 10 (remainder after division by 10) of the integer, so that is basically the last decimal digit.
/= 10 divides by 10. Since it's an integer division, the part after the comma is truncated, so this basically removes the last digit.
So, for a number 123, this happens;
n = n + 3;
sum = 123 / 10 = 12;
n = n + 2;
sum = 12 / 10 = 1;
n = n + 1;
So sum is a bad name, since it is actually the variable that contains the input and which is processed. n is actually the variable that contains the sum. You should initialize n to 0 and sum to the input integer to make this work properly.
So this is a program to calculate the sum of all digits in an integer.
How it works:
It takes the remainder of the number / 10 and iteratively adds it to a variable initialised to 0.
Sequence of steps:
Suppose sum = 2155, n = 0
In the first iteration,
n += sum % 10; //Here, n = n+ sum % 10. So, n will be evauated to 5 since, 2155 % 10 = 5
sum /= 10; // Here, sum = sum / 10, since sum is an integer, the value of sum will now be 2155 / 10 = 215
This happens iteratively until value of sum becomes 0 and value of n will be 2+1+5+5 = 13.
Hope this helps.

Getting the nearest value that returns true on a bool

If I wanted to get the nearest value to a number, but that value also has to return true on a bool called IsMultipleOf7 which returns true on numbers that are multiples of 7.
For example, I have a int x = 523. So the nearest multiple of 7 is 525, so my bool would return true 525.
How can I get that number?
This function will return the closest multiple of 7 or the number itself if it is a multiple of 7
public int GetClosestNumber(int number, out bool isMultipleOf7)
{
// if the number is a multiple of 7 isMultipleOf7 is set to true
isMultipleOf7 = number%7 == 0;
if (isMultipleOf7)
{
// if it's a multiple of 7 then the closest one is the number itself
return number;
}
// if it's not a multiple of 7 then try find the closest.
var lower = number - (number % 7);
var upper = (number + 7) - (number %7);
var diffL = Math.Abs(number - lower);
var diffU = Math.Abs(number - upper);
return diffL > diffU ? upper : lower;
}
And here's a usage example:
bool IsMultipleOf7;
// Following line will output: Closest multiple of 7 is: 525
Console.WriteLine("Closest multiple of 7 is: {0}",
GetClosestNumber(523, out IsMultipleOf7));
// Following line will output: The number itself is not a multiple of 7"
Console.WriteLine("The number itself is {0} a multiple of 7",
IsMultipleOf7 ? string.Empty: "not");
Live demo is also available here
int x = 523;
while ((int)x/7!=(decimal)x/7){
x++;
}
return x;
int x = 523;
int result = ((x / 7) + 1) * 7;
You may need a more complex formula, if your number is dividable by 7 and should stay the same number. Or maybe you have simplified your problem too much?
There are two ways I can think of. The first is the brute force method I commented about. If you start with the number x, test it. If it works, hooray! If not, try adding one to x and test. Then subtract one from x and test. Then do this with two, and three, testing up and down at the same time. Once your test returns true, you have located (one of) the closest number(s) that work. This method is a general one and will work with any test function.
Because we know you are using IsMultipleOf7 as the test, a smarter method could be possible. Imagine the time it would take if your test was instead IsMultipleOf999999999! So many numbers might have to tested before hitting the closest. Instead, some math can be used. First, compute x modulo 7 (for IsMultipleOf7), written x % 7 in C(++). This value tells you how far x is from the largest multiple of 7 LESS than x. If this value is 0, x is a multiple of 7. If the value is 1, 2 or 3, x minus the value is the closest multiple. If the value is 4, 5 or 6, x plus the difference to make 7 (7 - value) is the closest multiple.
Some pseudo-code:
x = 523
value = x modulo 7
if(value == 0):
return x
if(value < 4): // that is, less than half of 7
return x - value
otherwise
return x + (7 - value)
x=7*Math.Round(((float)x)/7.0)
^Simplest solution right there ;)
No need for all of this looping and stuff.
divide by 7, if the decimals are less than 0.5 then the nearest denominator is floored, else ceiling. Round() does that for you, then just multiply your new int by 7 to create a number evenly divisible by 7 (since it was an int being multiplied by 7). It will get the closest value above or below. No need for bool at all. Make sure you cast float onto x so that it can be divided by 7 without causing flooring with integer logic.

Getting Factors of a Number

I'm trying to refactor this algorithm to make it faster. What would be the first refactoring here for speed?
public int GetHowManyFactors(int numberToCheck)
{
// we know 1 is a factor and the numberToCheck
int factorCount = 2;
// start from 2 as we know 1 is a factor, and less than as numberToCheck is a factor
for (int i = 2; i < numberToCheck; i++)
{
if (numberToCheck % i == 0)
factorCount++;
}
return factorCount;
}
The first optimization you could make is that you only need to check up to the square root of the number. This is because factors come in pairs where one is less than the square root and the other is greater.
One exception to this is if n is an exact square then its square root is a factor of n but not part of a pair.
For example if your number is 30 the factors are in these pairs:
1 x 30
2 x 15
3 x 10
5 x 6
So you don't need to check any numbers higher than 5 because all the other factors can already be deduced to exist once you find the corresponding small factor in the pair.
Here is one way to do it in C#:
public int GetFactorCount(int numberToCheck)
{
int factorCount = 0;
int sqrt = (int)Math.Ceiling(Math.Sqrt(numberToCheck));
// Start from 1 as we want our method to also work when numberToCheck is 0 or 1.
for (int i = 1; i < sqrt; i++)
{
if (numberToCheck % i == 0)
{
factorCount += 2; // We found a pair of factors.
}
}
// Check if our number is an exact square.
if (sqrt * sqrt == numberToCheck)
{
factorCount++;
}
return factorCount;
}
There are other approaches you could use that are faster but you might find that this is already fast enough for your needs, especially if you only need it to work with 32-bit integers.
Reducing the bound of how high you have to go as you could knowingly stop at the square root of the number, though this does carry the caution of picking out squares that would have the odd number of factors, but it does help reduce how often the loop has to be executed.
Looks like there is a lengthy discussion about this exact topic here: Algorithm to calculate the number of divisors of a given number
Hope this helps
The first thing to notice is that it suffices to find all of the prime factors. Once you have these it's easy to find the number of total divisors: for each prime, add 1 to the number of times it appears and multiply these together. So for 12 = 2 * 2 * 3 you have (2 + 1) * (1 + 1) = 3 * 2 = 6 factors.
The next thing follows from the first: when you find a factor, divide it out so that the resulting number is smaller. When you combine this with the fact that you need only check to the square root of the current number this is a huge improvement. For example, consider N = 10714293844487412. Naively it would take N steps. Checking up to its square root takes sqrt(N) or about 100 million steps. But since the factors 2, 2, 3, and 953 are discovered early on you actually only need to check to one million -- a 100x improvement!
Another improvement: you don't need to check every number to see if it divides your number, just the primes. If it's more convenient you can use 2 and the odd numbers, or 2, 3, and the numbers 6n-1 and 6n+1 (a basic wheel sieve).
Here's another nice improvement. If you can quickly determine whether a number is prime, you can reduce the need for division even further. Suppose, after removing small factors, you have 120528291333090808192969. Even checking up to its square root will take a long time -- 300 billion steps. But a Miller-Rabin test (very fast -- maybe 10 to 20 nanoseconds) will show that this number is composite. How does this help? It means that if you check up to its cube root and find no factors, then there are exactly two primes left. If the number is a square, its factors are prime; if the number is not a square, the numbers are distinct primes. This means you can multiply your 'running total' by 3 or 4, respectively, to get the final answer -- even without knowing the factors! This can make more of a difference than you'd guess: the number of steps needed drops from 300 billion to just 50 million, a 6000-fold improvement!
The only trouble with the above is that Miller-Rabin can only prove that numbers are composite; if it's given a prime it can't prove that the number is prime. In that case you may wish to write a primality-proving function to spare yourself the effort of factoring to the square root of the number. (Alternately, you could just do a few more Miller-Rabin tests, if you would be satisfied with high confidence that your answer is correct rather than a proof that it is. If a number passes 15 tests then it's composite with probability less than 1 in a billion.)
You can limit the upper limit of your FOR loop to numberToCheck / 2
Start your loop counter at 2 (if your number is even) or 3 (for odd values). This should allow you to check every other number dropping your loop count by another 50%.
public int GetHowManyFactors(int numberToCheck)
{
// we know 1 is a factor and the numberToCheck
int factorCount = 2;
int i = 2 + ( numberToCheck % 2 ); //start at 2 (or 3 if numberToCheck is odd)
for( ; i < numberToCheck / 2; i+=2)
{
if (numberToCheck % i == 0)
factorCount++;
}
return factorCount;
}
Well if you are going to use this function a lot you can use modified algorithm of Eratosthenes http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes and store answars for a interval 1 to Max in array. It will run IntializeArray() once and after it will return answers in 0(1).
const int Max =1000000;
int arr [] = new int [Max+1];
public void InitializeArray()
{
for(int i=1;i<=Max;++i)
arr[i]=1;//1 is factor for everyone
for(int i=2;i<=Max;++i)
for(int j=i;i<=Max;i+=j)
++arr[j];
}
public int GetHowManyFactors(int numberToCheck)
{
return arr[numberToCheck];
}
But if you are not going to use this function a lot I think best solution is to check unitll square root.
Note: I have corrected my code!
An easy to implement algorithm that will bring you much farther than trial division is Pollard Rho
Here is a Java implementation, that should be easy to adapt to C#: http://www.cs.princeton.edu/introcs/78crypto/PollardRho.java.html
https://codility.com/demo/results/demoAAW2WH-MGF/
public int solution(int n) {
var counter = 0;
if (n == 1) return 1;
counter = 2; //1 and itself
int sqrtPoint = (Int32)(Math.Truncate(Math.Sqrt(n)));
for (int i = 2; i <= sqrtPoint; i++)
{
if (n % i == 0)
{
counter += 2; // We found a pair of factors.
}
}
// Check if our number is an exact square.
if (sqrtPoint * sqrtPoint == n)
{
counter -=1;
}
return counter;
}
Codility Python 100 %
Here is solution in python with little explanation-
def solution(N):
"""
Problem Statement can be found here-
https://app.codility.com/demo/results/trainingJNNRF6-VG4/
Codility 100%
Idea is count decedent factor in single travers. ie. if 24 is divisible by 4 then it is also divisible by 8
Traverse only up to square root of number ie. in case of 24, 4*4 < 24 but 5*5!<24 so loop through only i*i<N
"""
print(N)
count = 0
i = 1
while i * i <= N:
if N % i == 0:
print()
print("Divisible by " + str(i))
if i * i == N:
count += 1
print("Count increase by one " + str(count))
else:
count += 2
print("Also divisible by " + str(int(N / i)))
print("Count increase by two count " + str(count))
i += 1
return count
Example by run-
if __name__ == '__main__':
# result = solution(24)
# result = solution(35)
result = solution(1)
print("")
print("Solution " + str(result))
"""
Example1-
24
Divisible by 1
Also divisible by 24
Count increase by two count 2
Divisible by 2
Also divisible by 12
Count increase by two count 4
Divisible by 3
Also divisible by 8
Count increase by two count 6
Divisible by 4
Also divisible by 6
Count increase by two count 8
Solution 8
Example2-
35
Divisible by 1
Also divisible by 35
Count increase by two count 2
Divisible by 5
Also divisible by 7
Count increase by two count 4
Solution 4
Example3-
1
Divisible by 1
Count increase by one 1
Solution 1
"""
Github link
I got pretty good results with complexity of O(sqrt(N)).
if (N == 1) return 1;
int divisors = 0;
int max = N;
for (int div = 1; div < max; div++) {
if (N % div == 0) {
divisors++;
if (div != N/div) {
divisors++;
}
}
if (N/div < max) {
max = N/div;
}
}
return divisors;
Python Implementation
Score 100% https://app.codility.com/demo/results/trainingJ78AK2-DZ5/
import math;
def solution(N):
# write your code in Python 3.6
NumberFactor=2; #one and the number itself
if(N==1):
return 1;
if(N==2):
return 2;
squareN=int(math.sqrt(N)) +1;
#print(squareN)
for elem in range (2,squareN):
if(N%elem==0):
NumberFactor+=2;
if( (squareN-1) * (squareN-1) ==N):
NumberFactor-=1;
return NumberFactor

Append a digit to an integer and make sure sum of each digits ends with 1

What is the algorithm in c# to do this?
Example 1:
Given n = 972, function will then append 3 to make 9723, because 9 + 7 + 2 + 3 = 21 (ends with 1). Function should return 3.
Example 2:
Given n = 33, function will then append 5 to make 335, because 3 + 3 + 5 = 11 (ends with 1). Function should return 5.
Algorithms are language independent. Asking for "an algorithm in C#" doesn't make much sense.
Asking for the algorithm (as though there is only one) is similarly misguided.
So, let's do this step by step.
First, we note that only the last digit of the result is meaningful. So, we'll sum up our existing digits, and then ignore all but the last one. A good way to do this is to take the sum modulo 10.
So, we have the sum of the existing digits, and we want to add another digit to that, so that the sum of the two ends in 1.
For the vast majority of cases, that will mean sum + newDigit = 11. Rearranging gives newDigit = 11 - sum
We can then take this modulo 10 (again) in order to reduce it to a single digit.
Finally, we multiply the original number by 10, and add our new digit to it.
The algorithm in general:
(10 - (sum of digits mod 10) + 1) mod 10
The answer of the above expression is your needed digit.
sum of digits mod 10 gives you the current remainder, when you subtract this from 10 you get the needed value for a remainder of 0. When you add 1 you get the needed value to get a remainder of 1. The last mod 10 gives you the answer as a 1 digit number.
So in C# something like this:
static int getNewValue(string s)
{
int sum = 0;
foreach (char c in s)
{
sum += Convert.ToInt32(c.ToString());
}
int newDigit = (10 - (sum % 10) + 1) % 10;
return newDigit;
}
Another alternative using mod once only
int sum = 0;
foreach (char c in s)
sum += Convert.ToInt32(c.ToString());
int diff = 0;
while (sum % 10 != 1)
{
sum++;
diff++;
}
if (diff > 0)
s += diff.ToString();
Well, it's easier in C++.
std::string s = boost::lexical_cast<string>( i );
i = i * 10 + 9 - std::accumulate( s.begin(), s.end(), 8 - '0' * s.size() ) % 10;
Addicted to code golf…

Categories