Find the number - c#

This is a problem statement.
Consider a number 2345. If you multiply its digits then you get the number 120. Now if you again multiply digits of 120 then you will get number 0 which is a one digit number. If I add digits of 2345 then I will get 14. If I add digits of 14 then I will get 5 which is a one digit number.
Thus any number can be converted into two one digit numbers in some number of steps. You can see 2345 is converted to 0 by using multiplication of digits in 2 steps and it is converted to 5 by using addition of digits in 2 steps. Now consider any number N. Let us say that it can be converted by multiplying digits to a one digit number d1 in n1 steps and by adding digits to one digit number d2 in n2 steps.
Your task is to find smallest number greater than N and less than 1000000000 which can be converted by multiplying its digits to d1 in less than or equal to n1 steps and by adding its digits to d2 in less than or equal to n2 steps.
How to solve it in C#...

I think you're simply approaching / interpreting the problem incorrectly; here's a stab in the dark:
using System;
using System.Diagnostics;
static class Program
{
static void Main()
{
// check our math first!
// You can see 2345 is converted to 0 by using multiplication of digits in 2 steps
int value, steps;
value = MultiplyToOneDigit(2345, out steps);
Debug.Assert(value == 0);
Debug.Assert(steps == 2);
// and it is converted to 5 by using addition of digits in 2 steps
value = SumToOneDigit(2345, out steps);
Debug.Assert(value == 5);
Debug.Assert(steps == 2);
// this bit is any random number
var rand = new Random();
for (int i = 0; i < 10; i++)
{
int N = rand.Next(0, MAX);
int result = Execute(N);
Console.WriteLine("For N={0}, our answer is {1}", N, result);
}
}
const int MAX = 1000000000;
//Now consider any number N.
static int Execute(int N)
{
// Let us say that it can be converted by multiplying digits to a one digit number d1 in n1
// steps and by adding digits to one digit number d2 in n2 steps.
int n1, n2;
int d1 = MultiplyToOneDigit(N, out n1),
d2 = SumToOneDigit(N, out n2);
// Your task is to find smallest number greater than N and less than 1000000000
for (int i = N + 1; i < MAX; i++)
{
int value, steps;
// which can be converted by multiplying its digits to d1 in less than or equal to n1 steps
value = MultiplyToOneDigit(i, out steps);
if (value != d1 || steps > n1) continue; // no good
// and by adding its digits to d2 in less than or equal to n2 steps.
value = SumToOneDigit(i, out steps);
if(value != d2 || steps > n2) continue; // no good
return i;
}
return -1; // no answer
}
static int MultiplyToOneDigit(int value, out int steps)
{
steps = 0;
while (value > 10)
{
value = MultiplyDigits(value);
steps++;
}
return value;
}
static int SumToOneDigit(int value, out int steps)
{
steps = 0;
while (value > 10)
{
value = SumDigits(value);
steps++;
}
return value;
}
static int MultiplyDigits(int value)
{
int acc = 1;
while (value > 0)
{
acc *= value % 10;
value /= 10;
}
return acc;
}
static int SumDigits(int value)
{
int total = 0;
while (value > 0)
{
total += value % 10;
value /= 10;
}
return total;
}
}

There are two memory problems I can see; the first is the generation of lots of strings - you might want to approach that something like:
static int SumDigits(int value)
{
int total = 0;
while (value > 0)
{
total += value % 10;
value /= 10;
}
return total;
}
(which is completely untested)
The second problem is the huge list; you don't need to store (in lstString) every value just to find a minimum. Just keep track of the best you've done so far. Or if you need the data for every value, then: don't store them as a string. Indeed, the i can be implied anyway (from the position in the list/array), so all you would really need would be an int[] of the cnt values for every value. And int[1000000000] is 4GB just by itself, so would require the large-array support in recent .NET versions (<gcAllowVeryLargeObjects>). But much better would be: just don't store it.

But it's throwing System.OutOfMemoryException .
That simply mean you're running out of memory. Your limit is 1,000,000,000 or roughly 1G. Times 4 bytes for a string reference that's already too large for a 32 bit system. Even without the actual strings.
You can store your answers more compactly in an int[] array but that would still show the same problem.
So, lower your limit or compile and run on a 64 bit PC.

A for effort :)
Now doing together. You can of course do refactoring.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _17082903_smallest_greatest_number
{
class Program
{
static void Main(string[] args)
{
int N = 2344;
int n1 = 0;
int n2 = 0;
int d1 = SumDigits(N, ref n1);
int d2 = ProductDigits(N, ref n2);
bool sumFound = false, productFound = false;
for (int i = N + 1; i < 1000000000; i++)
{
if (!sumFound)
{
int stepsForSum = 0;
var res = SumDigits(i, ref stepsForSum);
if (res == d1 && stepsForSum <= n1)
{
Console.WriteLine("the smallest number for sum is: " + i);
Console.WriteLine(string.Format("sum result is {0} in {1} steps only", res, stepsForSum));
sumFound = true;
}
stepsForSum = 0;
}
if (!productFound)
{
int stepsForProduct = 0;
var res2 = ProductDigits(i, ref stepsForProduct);
if (res2 == d2 && stepsForProduct <= n2)
{
Console.WriteLine("the smallest number for product is: " + i);
Console.WriteLine(string.Format("product result is {0} in {1} steps only", res2, stepsForProduct));
productFound = true;
}
stepsForProduct = 0;
}
if (productFound && sumFound)
{
break;
}
}
}
static int SumDigits(int value, ref int numOfSteps)
{
int total = 0;
while (value > 0)
{
total += value % 10;
value /= 10;
}
numOfSteps++;
if (total < 10)
{
return total;
}
else
{
return SumDigits(total, ref numOfSteps);
}
}
static int ProductDigits(int value, ref int numOfSteps)
{
int total = 1;
while (value > 0)
{
total *= value % 10;
value /= 10;
}
numOfSteps++;
if (total < 10)
{
return total;
}
else
{
return ProductDigits(total, ref numOfSteps);
}
}
}
}

Related

Count All Prime Numbers that Can be Formed using Digits of a Given Number

I am facing a problem while solving this task.
I should write a program which find the count of prime numbers which can be created using digits of given number, but without repetition unless digit itself repeated in given number.
For example, program should give 5 as output for number = 123. Because
{1, 2, 3, 12, 13, 21, 23, 123, 132, 213, 231, 312, 321}
has 5 prime numbers.
But if given number = 133 then program should count prime number from this list :
{1, 3, 13, 31, 33, 133, 313, 331}
Is there any way to write this program without using array? I have searched every source, but still cannot find a solution. If you have any idea, please help.
I am trying to write something like that. But it is still not working. It is not creating number as I want. One-digit numbers is a little bit closer than 3-digit when I enter 123 . Output is like that:
enter image description here
System.Console.WriteLine("Enter the number: ");
int number = Convert.ToInt32(Console.ReadLine());
int enteredNumber = number;
int length = 0;
while (number != 0)
{
length++;
number /= 10;
}
System.Console.WriteLine($"{length} length");
number = enteredNumber;
int nDigit = 1;
int count = 0;
int temp = number;
while (nDigit <= length)
{
int n = nDigit;
while (number != 0)
{
int digit = number % 10;
if (nDigit == 1 && isPrime(digit))
{
System.Console.WriteLine("1-digit prime number : " + digit);
count++;
}
else
{
int tempNewNumber = digit * Convert.ToInt32(Math.Pow(10, Convert.ToDouble(nDigit - 1)));
int newNumber = tempNewNumber;
while (temp != 0)
{
if (nDigit - 2 >= 0)
{
newNumber += (temp % 10) * Convert.ToInt32(Math.Pow(10, Convert.ToDouble(nDigit - 2)));
nDigit--;
}
if (nDigit == 1)
{
System.Console.WriteLine("in while : " + newNumber);
if (isPrime(newNumber))
{
System.Console.WriteLine("prime number : " + newNumber);
count++;
}
newNumber = tempNewNumber;
nDigit = n;
}
temp /= 10;
}
nDigit = n;
temp = enteredNumber;
}
number /= 10;
}
number = enteredNumber;
nDigit++;
}
System.Console.WriteLine("Count : " + count);
}
static bool isPrime(int num)
{
if (num <= 1) return false;
int i = 2;
while (i <= num / 2)
{
if (num % i == 0)
return false;
i++;
}
return true;
}`
You can do what you want without arrays: Identify a number by the product of the nth prime number for each digit n.
If two numbers have the same id, they are digit-wise permutations of each other.
If the id of one number p is evenly divisibly by the id of another number q, then q has fewer digits than p, but all digits of q can also found in p.
You can now test all numbers in the possible range, for example all numbers with 3 or fewer digits, whether they can be made from the given digit. This is probably not very efficient, especially for large numbers, but hey! – no arrays. (And permutations of large sets have their own performance issues.)
The example code below finds the 16 permutations of 123, but it doesn't check whether the numbers are primes.
public class Permutor
{
static uint[] prime = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};
static uint code(uint n)
{
uint res = 1;
while (n > 0) {
res *= prime[n % 10];
n /= 10;
}
return res;
}
static uint ceiling(uint n)
{
uint c = 1;
while (n > 0) {
c *= 10;
n /= 10;
}
return c;
}
static void Main(string[] args)
{
uint num = 123;
uint id = code(num);
uint max = ceiling(num);
for (uint i = 1; i < max; i++) {
if (id % code(i) == 0) {
Console.WriteLine(i);
}
}
}
}
There's room for improvement. For example, the actual ceiling for 123 is, of course, 321, so you could try to find that from the code instead of overestimating the ciling to 1000.
When you look for primes, you don't need to visit every number. Except 2 and 3, all prime numbers are either 2*k - 1 or 2*k + 1.

count odd and even digits in a number

I try to write program that check the ratio between odd and even
digits in a given number. I've had some problems with this code:
static void Main(string[] args)
{
int countEven = 0 ;
int countOdd = 0 ;
Console.WriteLine("insert a number");
int num = int.Parse(Console.ReadLine());
int length = num.GetLength;
for (int i = 0;i<length ; i++)
{
if((num/10)%2) == 0)
int countEven++;
}
}
any ideas?
The problem is that int does not have a length, only the string representation of it has one.As an alternative to m.rogalski answer, you can treat the input as a string to get all the digits one by one. Once you have a digit, then parsing it to int and checking if it is even or odd is trivial.Would be something like this:
int countEven = 0;
int countOdd = 0;
Console.WriteLine("insert a number");
string inputString = Console.ReadLine();
for (int i = 0; i < inputString.Length; i++)
{
if ((int.Parse(inputString[i].ToString()) % 2) == 0)
countEven++;
else
countOdd++;
}
Linq approach
Console.WriteLine("insert a number");
string num = Console.ReadLine(); // check for valid number here?
int countEven = num.Select(x => x - '0').Count(x => x % 2 == 0);
int countOdd = num.Select(x => x - '0').Count(x => x % 2 != 0);
Let's assume your input is : 123456
Now all you have to do is to get the modulo from the division by ten : int m = num % 10;
After that just check if bool isEven = m % 2 == 0;
On the end you have to just divide your input number by 10 and repeat the whole process till the end of numbers.
int a = 123456, oddCounter = 0, evenCounter = 0;
do
{
int m = a % 10;
switch(m % 2)
{
case 0:
evenCounter++;
break;
default: // case 1:
oddCounter++;
break;
}
//bool isEven = m % 2 == 0;
}while( ( a /= 10 ) != 0 );
Online example
Made a small change to your code and it works perfectly
int countEven = 0;
int countOdd = 0;
Console.WriteLine( "insert a number" );
char[] nums = Console.ReadLine().ToCharArray();
for ( int i = 0; i < nums.Length; i++ )
{
if ( int.Parse( nums[i].ToString() ) % 2 == 0 )
{
countEven++;
}
else
{
countOdd++;
}
}
Console.WriteLine($"{countEven} even numbers \n{countOdd} odd numbers");
Console.ReadKey();
What I do is get each number as a a character in an array char[] and I loop through this array and check if its even or not.
If the Input number is a 32-bit integer (user pick the length of the number)
if asked:
The number of even digits in the input number
Product of odd digits in the input number
The sum of all digits of the input number
private void button1_Click(object sender, EventArgs e) {
int num = ConvertToInt32(textBox1.Text);
int len_num = textBox1.Text.Length;
int[] arn = new int[len_num];
int cEv = 0; pOd = 0; s = 0;
for (int i = len_num-1; i >= 0; i--) { // loop until integer length is got down to 1
arn[i] = broj % 10; //using the mod we put the last digit into a declared array
if (arn[i] % 2 == 0) { // then check, is current digit even or odd
cEv++; // count even digits
} else { // or odd
if (pOd == 0) pOd++; // avoid product with zero
pOd *= arn [i]; // and multiply odd digits
}
num /= 10; // we divide by 10 until it's length is get to 1(len_num-1)
s += arn [i]; // sum of all digits
}
// and at last showing it in labels...
label2.Text = "a) The even digits count is: " + Convert.ToString(cEv);
label3.Text = "b) The product of odd digits is: " + Convert.ToString(pOd);
label4.Text = "c) The sum of all digits in this number is: " + Convert.ToString(s);
}
All we need in the interface is the textbox for entering the number, the button for the tasks, and labels to show obtained results. Of course, we have the same result if we use a classic form for the for loop like for (int i = 0; and <= len_num-1; i++) - because the essence is to count the even or odd digits rather than the sequence of the digits entry into the array
static void Main(string args[]) {
WriteLine("Please enter a number...");
var num = ReadLine();
// Check if input is a number
if (!long.TryParse(num, out _)) {
WriteLine("NaN!");
return;
}
var evenChars = 0;
var oddChars = 0;
// Convert string to char array, rid of any non-numeric characters (e.g.: -)
num.ToCharArray().Where(c => char.IsDigit(c)).ToList().ForEach(c => {
byte.TryParse(c.ToString(), out var b);
if (b % 2 == 0)
evenChars++;
else
oddChars++;
});
// Continue with code
}
EDIT:
You could also do this with a helper (local) function within the method body:
static void Main(string args[]) {
WriteLine("Please enter a number...");
var num = ReadLine();
// Check if input is a number
if (!long.TryParse(num, out _)) {
WriteLine("NaN!");
return;
}
var evenChars = 0;
var oddChars = 0;
// Convert string to char array, rid of any non-numeric characters (e.g.: -)
num.ToCharArray().Where(c => char.IsDigit(c)).ToList().ForEach(c => {
byte.TryParse(c.ToString(), out var b);
if (b % 2 == 0)
evenChars++;
else
oddChars++;
// Alternative method:
IsEven(b) ? evenChars++ : oddChars++;
});
// Continue with code
bool IsEven(byte b) => b % 2 == 0;
}
Why am I using a byte?
Dealing with numbers, it is ideal to use datatypes that don't take up as much RAM.
Granted, not as much an issue nowadays with multiple 100s of gigabytes possible, however, it is something not to be neglected.
An integer takes up 32 bits (4 bytes) of RAM, whereas a byte takes up a single byte (8 bits).
Imagine you're processing 1 mio. single-digit numbers, and assigning them each to integers. You're using 4 MiB of RAM, whereas the byte would only use up 1 MiB for 1 mio. numbers.
And seeming as a single-digit number (as is used in this case) can only go up to 9 (0-9), you're wasting a potential of 28 bits of memory (2^28) - whereas a byte can only go up to 255 (0-255), you're only wasting a measly four bits (2^4) of memory.

An algorithm for a number divisible to n

At first user gives a number (n) to program, for example 5.
the program must find the smallest number that can be divided to n (5).
and this number can only consist of digits 0 and 9 not any other digits.
for example if user gives 5 to program.
numbers that can be divided to 5 are:
5, 10, 15, 20, 25, 30, ..., 85, 90, 95, ...
but 90 here is the smallest number that can be divided to 5 and also consist of digits (0 , 9). so answer for 5 must be 90.
and answer for 9 is 9, because it can be divided to 9 and consist of digit (9).
my code
string a = txtNumber.Text;
Int64 x = Convert.ToInt64(a);
Int64 i ,j=1,y=x;
bool t = false;
for (i = x + 1; t == false; i++)
{
if (i % 9 == 0 && i % 10 == 0 && i % x == 0)
{
j = i;
for (; (i /= 10) != 0; )
{
i /= 10;
if (i == 0)
t = true;
continue;
}
}
}
lblAnswer.Text = Convert.ToString(j);
If you're happy to go purely functional then this works:
Func<IEnumerable<long>> generate = () =>
{
Func<long, IEnumerable<long>> extend =
x => new [] { x * 10, x * 10 + 9 };
Func<IEnumerable<long>, IEnumerable<long>> generate2 = null;
generate2 = ns =>
{
var clean = ns.Where(n => n > 0).ToArray();
return clean.Any()
? clean.Concat(generate2(clean.SelectMany(extend)))
: Enumerable.Empty<long>();
};
return generate2(new[] { 9L, });
};
Func<long, long?> f = n =>
generate()
.Where(x => x % n == 0L)
.Cast<long?>()
.FirstOrDefault();
So rather than iterate through all possible values and test for 0 & 9 and divisibility, this just generates only numbers with 0 & 9 and then only tests for visibility. It is much faster this way.
I can call it like this:
var result = f(5L); // 90L
result = f(23L); //990909L
result = f(123L); //99999L
result = f(12321L); //90900999009L
result = f(123212L); //99909990090000900L
result = f(117238L); //990990990099990990L
result = f(1172438L); //null == No answer
These results are super fast. f(117238L) returns a result on my computer in 138ms.
You can try this way :
string a = txtNumber.Text;
Int64 x = Convert.ToInt64(a);
int counter;
for (counter = 1; !isValid(x * counter); counter++)
{
}
lblAnswer.Text = Convert.ToString(counter*x);
code above works by searching multiple of x incrementally until result that satisfy criteria : "consist of only 0 and or 9 digits" found. By searching only multiple of x, it is guaranteed to be divisible by x. So the rest is checking validity of result candidate, in this case using following isValid() function :
private static bool isValid(int number)
{
var lastDigit = number%10;
//last digit is invalid, return false
if (lastDigit != 0 & lastDigit != 9) return false;
//last digit is valid, but there is other digit(s)
if(number/10 >= 1)
{
//check validity of digit(s) before the last
return isValid(number/10);
}
//last digit is valid, and there is no other digit. return true
return true;
}
About strange empty for loop in snippet above, it is just syntactic sugar, to make the code a bit shorter. It is equal to following while loop :
counter = 1;
while(!isValid(input*counter))
{
counter++;
}
Use this simple code
int inputNumber = 5/*Or every other number, you can get this number from input.*/;
int result=1;
for (int i = 1; !IsOk(result,inputNumber); i++)
{
result = i*inputNumber;
}
Print(result);
IsOk method is here:
bool IsOk(int result, int inputNumber)
{
if(result%inputNumber!=0)
return false;
if(result.ToString().Replace("9",string.Empty).Replace("0",string.Empty).Length!=0)
return false;
return true;
}
My first solution has very bad performance, because of converting a number to string and looking for characters '9' and '0'.
New solution:
My new solution has very good performance and is a technical approach since of using Breadth-first search(BFS).
Algorithm of this solution:
For every input number, test 9, if it is answer print it, else add 2 child numbers (90 & 99) to queue, and continue till finding answer.
int inputNumber = 5;/*Or every other number, you can get this number from input.*/
long result;
var q = new Queue<long>();
q.Enqueue(9);
while (true)
{
result = q.Dequeue();
if (result%inputNumber == 0)
{
Print(result);
break;
}
q.Enqueue(result*10);
q.Enqueue(result*10 + 9);
}
Trace of number creation:
9
90,99
900,909,990,999
9000,9009,9090,9099,9900,9909,9990,9999
.
.
.
I wrote this code for console, and i used goto command however it is not prefered but i could not write it with only for.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace main
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter your number");
Int64 x = Convert.ToInt64(Console.ReadLine());
Int64 y, j, i, k, z = x;
x = x + 5;
loop:
x++;
for (i = 0, y = x; y != 0; i++)
y /= 10;
for (j = x, k = i; k != 0; j /= 10, k--)
{
if (j % 10 != 9)
if (j % 10 != 0)
goto loop;
}
if (x % z != 0)
goto loop;
Console.WriteLine("answer:{0}",x);
Console.ReadKey();
}
}
}

Split number into groups of 3 digits

I want to make a method that takes a variable of type int or long and returns an array of ints or longs, with each array item being a group of 3 digits. For example:
int[] i = splitNumber(100000);
// Outputs { 100, 000 }
int[] j = splitNumber(12345);
// Outputs { 12, 345 }
int[] k = splitNumber(12345678);
// Outputs { 12, 345, 678 }
// Et cetera
I know how to get the last n digits of a number using the modulo operator, but I have no idea how to get the first n digits, which is the only way to make this method that I can think of. Help please!
Without converting to string:
int[] splitNumber(int value)
{
Stack<int> q = new Stack<int>();
do
{
q.Push(value%1000);
value /= 1000;
} while (value>0);
return q.ToArray();
}
This is simple integer arithmetic; first take the modulo to get the right-most decimals, then divide to throw away the decimals you already added. I used the Stack to avoid reversing a list.
Edit: Using log to get the length was suggested in the comments. It could make for slightly shorter code, but in my opinion it is not better code, because the intent is less clear when reading it. Also, it might be less performant due to the extra Math function calls. Anyways; here it is:
int[] splitNumber(int value)
{
int length = (int) (1 + Math.Log(value, 1000));
var result = from n in Enumerable.Range(1,length)
select ((int)(value / Math.Pow(1000,length-n))) % 1000;
return result.ToArray();
}
By converting into a string and then into int array
int number = 1000000;
string parts = number.ToString("N0", new NumberFormatInfo()
{
NumberGroupSizes = new[] { 3 },
NumberGroupSeparator = "."
});
By using Maths,
public static int[] splitNumberIntoGroupOfDigits(int number)
{
var numberOfDigits = Math.Floor(Math.Log10(number) + 1); // compute number of digits
var intArray = new int[Convert.ToInt32(numberOfDigits / 3)]; // we know the size of array
var lastIndex = intArray.Length -1; // start filling array from the end
while (number != 0)
{
var lastSet = number % 1000;
number = number / 1000;
if (lastSet == 0)
{
intArray[lastIndex] = 0; // set of zeros
--lastIndex;
}
else if (number == 0)
{
intArray[lastIndex] = lastSet; // this could be your last set
--lastIndex;
}
else
{
intArray[lastIndex] = lastSet;
--lastIndex;
}
}
return intArray;
}
Try converting it to string first and do the parsing then convert it back to number again
Convert to string
Get length
If length modulus 3 == 0
String substring it into ints every 3
else if
Find remainder such as one or two left over
Substring remainder off of front of string
Then substring by 3 for the rest
You can first find out how large the number is, then use division to get the first digits, and modulo to keep the rest:
int number = 12345678;
int len = 1;
int div = 1;
while (number >= div * 1000) {
len++;
div *= 1000;
}
int[] result = new int[len];
for (int i = 0; i < result.Length; i++) {
result[i] = number / div;
number %= div;
div /= 1000;
}
You can use this with the System.Linq namespace from .NET 3.5 and above:
int[] splitNumber(long value)
{
LinkedList<int> results = new LinkedList<int>();
do
{
int current = (int) (value % 1000);
results.AddFirst(current);
value /= 1000;
} while (value > 0);
return results.ToArray();// Extension method
}
I use LinkedList<int> to avoid having to Reverse a list before returning. You could also use Stack<int> for the same purpose, which would only require .NET 2.0:
int[] splitNumber(long value)
{
Stack<int> results = new Stack<int>();
do
{
int current = (int) (value % 1000);
results.Push(current);
value /= 1000;
} while (value > 0);
return results.ToArray();
}

Solving Mathematical logics, placing digits in third number from digits of first and second number

I have two numbers.
First Number is 2875 &
Second Number is 852145
Now I need a program which create third number.
Third Number will be 2885725145
The logic is
First digit of third number is first digit of first number.
Second digit of third number is first digit of second number.
Third digit of third number is second digit of first number.
Fourth digit of third number is second digit of second number;
so on.
If any number has remaining digits then that should be appended at last.
I do not want to convert int to string.
int CreateThirdNumber(int firstNumber, int secondNumber)
{
}
So can anyone suggest me any solution to this problem?
I do not want to convert int to string.
Why?
Without converting to string
Use Modulus and Division operator.
With converting to string
Convert them to string. Use .Substring() to extract and append value in a string. Convert appended string to integer.
Here's a bit that will give you a lead:
Say you have the number 2875. First, you need to determine it's length, and then, extract the first digit
This can be easily calculated:
int iNumber = 2875;
int i = 10;
int iLength = 0;
while (iNumber % i <= iNumber){
iLength++;
i *= 10;
}
// iNumber is of length iLength, now get the first digit,
// using the fact that the division operator floors the result
int iDigit = iNumber / pow(10, iLength-1);
// Thats it!
First a little advice: if you use int in C#, then the value in your example (2885725145) is bigger than int.MaxValue; (so in this case you should use long instead of int).
Anyway here is the code for your example, without strings.
int i1 = 2875;
int i2 = 852145;
int i3 = 0;
int i1len = (int)Math.Log10(i1) + 1;
int i2len = (int)Math.Log10(i2) + 1;
i3 = Math.Max(i1, i2) % (int)Math.Pow(10, Math.Max(i1len, i2len) - Math.Min(i1len, i2len));
int difference = (i1len - i2len);
if (difference > 0)
i1 /= (int)Math.Pow(10, difference);
else
i2 /= (int)Math.Pow(10, -difference);
for (int i = 0; i < Math.Min(i1len, i2len); i++)
{
i3 += (i2 % 10) * (int)Math.Pow(10, Math.Max(i1len, i2len) - Math.Min(i1len, i2len) + i * 2);
i3 += (i1 % 10) * (int)Math.Pow(10, Math.Max(i1len, i2len) - Math.Min(i1len, i2len) + i * 2 + 1);
i1 /= 10;
i2 /= 10;
}
I don't understand why you don't want to use strings (is it homework?). Anyway this is another possible solution:
long CreateThirdNumber(long firstNumber, long secondNumber)
{
long firstN = firstNumber;
long secondN = secondNumber;
long len1 = (long)Math.Truncate(Math.Log10(firstNumber));
long len2 = (long)Math.Truncate(Math.Log10(secondNumber));
long maxLen = Math.Max(len1, len2);
long result = 0;
long curPow = len1 + len2 + 1;
for (int i = 0; i <= maxLen; i++)
{
if (len1 >= i)
{
long tenPwf = (long)Math.Pow(10, len1 - i);
long firstD = firstN / tenPwf;
firstN = firstN % tenPwf;
result = result + firstD * (long)Math.Pow(10, curPow--);
}
if (len2 >= i)
{
long tenPws = (long)Math.Pow(10, len2 - i);
long secondD = secondN / tenPws;
result = result + secondD * (long)Math.Pow(10, curPow--);
secondN = secondN % tenPws;
}
}
return result;
}
This solves it:
#include <stdio.h>
int main(void)
{
int first = 2875,second = 852145;
unsigned int third =0;
int deci,evenodd ,tmp ,f_dec,s_dec;
f_dec = s_dec =1;
while(first/f_dec != 0 || second/s_dec != 0) {
if(first/f_dec != 0) {
f_dec *=10;
}
if( second/s_dec != 0) {
s_dec *= 10;
}
}
s_dec /=10; f_dec/=10;
deci = s_dec*f_dec*10;
evenodd =0;tmp =0;
while(f_dec != 0 || s_dec !=0 ) {
if(evenodd%2 == 0 && f_dec !=0 ) {
tmp = (first/f_dec);
first -=(tmp*f_dec);
tmp*=deci;
third+=tmp;
f_dec/=10;
deci/=10;
}
if(evenodd%2 != 0 && s_dec != 0) {
tmp= (second/s_dec);
second -=(tmp*s_dec);
//printf("tmp:%d\n",tmp);
tmp*=deci;
third += tmp;
s_dec/=10;
deci/=10;
}
evenodd++;
}
printf("third:%u\ncorrct2885725145\n",third);
return 0;
}
output:
third:2885725145
corrct2885725145
#include <stdio.h>
long long int CreateThirdNumber(int firstNumber, int secondNumber){
char first[11],second[11],third[21];
char *p1=first, *p2=second, *p3=third;
long long int ret;
sprintf(first, "%d", firstNumber);
sprintf(second, "%d", secondNumber);
while(1){
if(*p1)
*p3++=*p1++;
if(*p2)
*p3++=*p2++;
if(*p1 == '\0' && *p2 == '\0')
break;
}
*p3='\0';
sscanf(third, "%lld", &ret);
return ret;
}
int main(){
int first = 2875;
int second = 852145;
long long int third;
third = CreateThirdNumber(first, second);
printf("%lld\n", third);
return 0;
}

Categories

Resources