Almost all my input parameters work except for some larger number inputs for my hexadecimal addition program. My program asks user to input two numbers and it would give out the sum of the two numbers. However, the number should be only 10 digits long, and if it exceeds 10 digits it should output an Addition Overflow.
If I input "1" for first number and "ffffffffff" (10 digits) for my second number I would get an output of "Addition Overflow.". (Correct)
However, if my first number were to be a "0" and second number to still be "ffffffffff" I would get an "Addition Overflow." which is incorrect. The output should still be "ffffffffff"
When you take the final carry, and shift everything over in this loop:
if (c != 0){
for(i = digits; i >= 0; i--)
answer[i] = answer[i-1];
answer[0] = hex[c];
}
You need to increment digits by one, as you have now added another digit at the end.
Then you need to change this statement:
if(digits > length - 1)
to this statement:
if(digits > length)
That will fix your problem.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm supposed to write 5 pseudocodes for algorithms below and I'm kinda stuck. The things I've done are below the tasks, I know last 3 are meaningless. Would appreciate any help or tips. Thanks
• Printing the largest number from the input
Title: Print Largest Number From Input
//works with number inputs
max=0
number= getNumber()
read number
if number == NONE
print (“NO VALID DATA”)
while number != NONE
if number > max
max = number
• Printing the largest even integer value from the input
Title: Print Largest Even Integer Number From Input
//works with even integer inputs
max=0
integer number= getNumber()
read_integer number
if number == NONE
print “NO VALID DATA”
if number % 2 == 0
print(“NO VALID DATA”)
while number != NONE && number % 2 != 0
if number > max
max = number
• Printing the sum of all input integers
Title: Print Sum of All Input Integers
int Number= getNumber()
read_integer Number
if Number == NONE
print(“NO VALID DATA”)
if Number != NONE
li.append(Number)
while li.length == n
print li[1] + li[2] + li[3] + ……. + li[n]
• Printing the arithmetic mean of all input numbers
Title: Print Arithmetic Mean of All Input Numbers
Number= getNumber()
read Number
if Number == NONE
print(“NO VALID DATA”)
if Number != NONE
li.append(Number)
while li.length == n
print li[1] + li[2] + li[3] + ……. + li[n] / n
• Printing all values greater or equal to the arithmetic mean of all input numbers
Title: Print All Values Greater Than or Equal to the Aritmetic Mean of All Input Numbers
Number= getNumber()
read Number
if Number == NONE
print(“NO VALID DATA”)
if Number != NONE
li.append(Number)
while li.length == n
arithmetic_mean = li[1] + li[2] + li[3] + ……. + li[n] / n
print(“”)
I'm guessing this is for class homework, so I wont provide full answers, but I'll try to help.
1. Print the largest number from the input
max = 0
// Assume that getNumber reads an input from the user and returns NONE if it is not a valid number
number = getNumber()
// If they never enter a number, give an error
if number == NONE:
print(“NO VALID DATA”)
exit() // exit the program
// Keep doing the following until number is set to NONE
while number != NONE:
if number > max:
max = number
number = getNumber()
print("The largest number is:")
print(max)
It seems like you basically have the right idea here. One thing to remember is that you have to getNumber() inside the loop. Otherwise, the value of number will never change because you only read the input once.
Note: this algorithm doesn't work if they only ever enter negative numbers. Setting max to negative infinity would fix that.
2. Print the largest even integer value from the input
This is exactly the same idea. The only change you have to make is ignoring every number that isn't even. You have the right idea for checking even-ness with the % operator.
Be careful where you make this check, though. If you check in the condition of the while loop, like you do in your code, then the loop will exit (and your program will stop) as soon as they enter an odd number. If you don't want that, then keep the loop running and just don't ever set max to be an odd number.
3. Print the sum of all input integers
It seems like your idea here is to save all the numbers they input to a list and then sum up the list at the end. That would work fine if you want to do that, but it's not necessary. Just like you kept track of a running max value, you could keep track of a running sum. Just add your the input to it each time. This is generally called the "accumulator pattern" if you want to look it up.
4. Print the arithmetic mean of all input numbers
Again, it looks like you are trying to store all the numbers in a list. Again, not necessary. Calculating the mean is just like calculating the sum except you need to divide by the number of inputs at the end. So, in addition to keeping track of the sum, you need to add an additional "accumulator" for n and just add 1 to it each time.
Also, it looks like you might be a little confused about what while does. while works just like if. It checks if a condition is true, and, if it is, it runs the code beneath it. The only difference is that while will keep running that code again and again until the condition is false. So the line while li.length == n doesn't make any sense. you haven't declared what n is before hand, so it can't make this comparison. I'm guessing you meant to do something like:
while number != NONE:
n = li.length
Here, you are assigning n to be the length of the list, instead of checking if the list length is equal to n or not.
5. Print all values greater or equal to the arithmetic mean of all input numbers
Here, we actually need to save all the inputs to a list, because we can't know what the mean is until we have seen all the numbers.
I would break this into three parts. First, just get all the input numbers and save them to a list. Then, calculate the mean of the list. Lastly, step through the list and print every value that's larger than the mean.
For part 1, just use the same pattern with a while loop that you have been since the first problem, but append number to a list instead of adding it to a sum.
For part 2, you need to calculate the sum of the list. In your code, you wrote li[1] + li[2] + li[3] + ……. + li[n]. The way you express this in code is probably with a for loop. I recommend looking up for loops for the language you are working in and seeing how they work. In some languages, you might be able to do something like this:
sum = 0
for number in list:
sum = sum + number
or, it might look like this:
sum = 0
for index in 0...list.length:
sum = sum + list[index]
For part 3, now that you have calculated the mean, you just need to loop through the numbers again and print the ones that are bigger than the mean.
for number in list:
if number > mean:
print(number)
I need a help. the problem is finding a symmetric numbers when shining in a mirror. (ex. 0, 1, 11, 101, 1521 (o) but 1221 & 1010 is not.)
enter image description here
Two numbers A and B are given with spaces between them.(input)
range is 0<=A, B<=10^18.
output is print symmetric numbers count from A to B.
ex) 0 100 (input)
7(output)
this is my codes in c++, but this codes occurred timeout because of wide number range. how solve this problem?
int main()
{
scanf("%d %d", &n,&m);
for(int i=n;i<=m;i++)
{
char s[19];
n=i;
int len=0;
do{
s[len++]=n%10;
n/=10;
} while(n>0);
len--;
int j = 0;
for(j=0;j<=len/2;j++)
{
if(s[j]==s[len-j] && (s[j]==1 || s[j]==8 || s[j]==0))
continue;
if( (s[j]==2 && s[len-j]==5) || (s[j]==5 && s[len-j]==2))
continue;
break;
}
if(j>len/2)
cnt++;
}
printf("%d\n",cnt);
return 0;
}
You've gone through a very painful process to see which of all the numbers are mirrors. Lukas Barth is on the right track, but it's even faster than that. You don't need to construct the numbers; just count how many there are.
First of all, you don't care at all about the second half of the number; by construction, given the left half, the right half is unique. Thus, all you have to do is to count left halves for each number length. This will solve all counting for powers of 10 that are entirely included in the range.
This makes it much easier. For the the ranges in which you have only part of the numbers (i.e. A and/or B is not a power of 10), you'll have to restrict leading digits on one end of the range or the other.
You're allowed leading zeros. Thus, you have five possibilities for each digit: 0, 1, 8, 2, 5. If you have an odd number of digits, then the middle digit must be its own mirror: 0, 1, 8.
So let's look at an example, 4-digit and 5-digit numbers. For the 4-digit numbers, you need only the first two. You have 5 possibilities for each of those digits. This yields 5*5, or 25 four-digit mirror numbers.
Now extend that for 5-digit numbers. You already know that there are exactly 25 two-digit starts. Add one of your three legal middle digits, and that gives 3*25, or 75 five-digit mirror numbers.
Extending this to the full solution is left as an exercise for the student.
Hi i am working on a random number generator which i faced a road block. I have done my program but i'm quite lost on how to do a loop for the C++ program to keep on looping. following below is the conditions for program:
The program prompts the user to enter a number.
This number determines the number of times the loop will repeat. The number ranges from 0 to 100. Validate this range.
The program uses a random number to generate a number from 0 to 9999 and then
checks if the generated number contains the digit 1, digit 2 or digit 3.
Please advise on how do i require to do a switch or while loop for point 3.
your inputs is greatly appreciated.
Easiest way to check would be to use the mod operation and division to extract every digit.
A loop would be something like
int randInt = randomFunction();
while(randInt > 0){
//Get Last Digit
int lastDigit = randInt % 10;
switch(lastDigit){
case 1:
// do something
break;
case 2:
// do something
break;
case 3:
// do something
break;
}
/*
Divide the number by 10 to remove the last digit.
Integers will automatically truncate remainders.
i.e int a = 21/10, a will = 2
*/
randInt /= 10;
}
I would like to output all similar numbers of a number, where:
Each pair of adjacent digits also occurs in the original number.
The new numbers has the same number of digits as the original
The order in which the numbers are generated doesn't matter
For example suppose I'm given a number 12314, then I have the pairs 12,23,31,14
I should generate [12314,31231,12312,23123].
If I'm given numbers like 52 or 11111 then I should get only 52/11111 respectively.
I have already written code that generates the pairs [12,23,31,14], and generate all possible permutations of this list of pairs. However, the permutations produce numbers that are longer than the original, and many of these permutations are invalid. For example, when 1214 appears in the permutation, the permutation is not valid since "21" is not in the original number.
I'd like to know how to proceed. It looks very inefficient to filter out the invalid ones from all permutations.
You could use recursion to generate the required numbers.
The idea is to maintain only valid numbers at any stage and to display when the original length and length of your number are equal.
// pairs[i][j] is true if j is immediately after i in the original number
bool pairs[10][10];
// curr_num is a valid number according to the constraint given
// curr_len is the number of digits in curr_num
// length is the number of digits in the number given
void generate(int curr_num, int curr_len, int length){
if(cur_len == length){
display curr_num;
} else {
// extract last digit & check what digits can follow that
int last = curr_num % 10;
for(int i = 0 ; i <= 9 ; i++)
if(pairs[last][i])
generate(curr_num * 10 + i , curr_len + 1, length);
}
}
for(digit in original_number)
generate(digit, 1, length);
You could optimize the code by making pairs an adjacency list than an adjacency matrix.
If I have a number like 12345, and I want an output of 2345, is there a mathematical algorithm that does this? The hack in me wants to convert the number to a string, and substring it. I know this will work, but I'm sure there has to be a better way, and Google is failing me.
Likewise, for 12345, if I want 1234, is there another algorithm that will do that? The best I can come up with is Floor(x / 10^(n)), where x is the input and n is the number of digits to strip, but I feel like there has to be a better way, and I just can't see it.
In the first case, don't you just want
n % 10000
i.e. the modulus wrt. 10000 ?
For your second case, if you're using integer arithmetic, just divide by 10. You might want to do this in a more 'explicit' fashion by modding with 10 to get the last digit, subtract and then divide (think of a shift in base 10).
Yes, the modulus operator (%) which is present in most languages, can return the n last digits:
12345 % 10^4 = 12345 % 10000 = 2345
Integral division (/ in C/C++/Java) can return the first n digits:
12345 / 10^4 = 12345 / 10000 = 1
Python 3.0:
>>> import math
>>> def remove_most_significant_digit(n, base=10):
... return n % (base ** int(math.log(n, base)))
...
>>> def remove_least_significant_digit(n, base=10):
... return int(n // base)
...
>>> remove_most_significant_digit(12345)
2345
>>> remove_least_significant_digit(12345)
1234
Converting to a string, and then using a substring method will ultimately be the fastest and best way, since you can just strip characters instead of doing math.
If you really don't want to do that though, you should use modulus (%), which gives the remainder of a division. 11 % 3 = 2, because 3 can only go into 11 three times (9). The remainder is then 2. 41 % 10 = 1, because 10 can go into 41 four times (40). The remainder is then 1.
For stripping the first digits, all you would have to do is mod the tens value that you want to get rid of. For stripping two digits from 12345, you should modulus by 1000. 1000 goes into 12345 twelve times, then the remainder will be 345, which is your answer. You would just need to find a way to find the tens value of the last digit you were trying to strip. Use x % (10^(n)), where x is input, and n is the lowest digit you want to strip.
For stripping the last digits, your way works just fine. What's easier than a quick formula like that?
I don't think there's any other approach than division for removing trailing numbers. It might be more efficient to do repeated integral division than to cast to a float, perform an exponent, then floor and cast back to an integer, but the basic idea remains the same.
Keep in mind that the operation is nearly identical for any base. To remove one trailing decimal digit, you do / 10. If you had 0b0111 and you wanted to remove one digit, it would have to be /2. Or you could have 0xff / 16 to get 0x0f.
You have to realize that numbers don't have digits, only strings do, and how many (and which) digits they have depends entirely on the base (which numbers don't have either). Internally, computers use what amounts to binary strings. So in general, manipulating base 10 digits requires you to convert the number to a string first - or do calculations that are the same you would do when converting it to a string. However, for your specific task of removing leading and trailing digits, these calculations (modulo and integer division) are very simple and much faster than converting the entire number.
i think that converting to string and then remove the first char wont do the trick.
i believe that the alg for converting to string is doing the div-mod routine, for optimization you might as well do the div-mod alg by yourself and manipulate it to your needs
Here is C++ code ... It's not tested.
int myPow ( int n , int k ){
int ret = 1;
for (int i=0;i<k;++i) ret*=n;
return ret;
}
int countDigits (int n ){
int count = 0;
while ( n )++count, n/=10;
return count;
}
int getLastDigits (int number , int numDigits ){
int tmp = myPow ( 10 , numDigits );
return number % tmp;
}
int getFirstDigits (int number, numDigits ){
int tmp = myPow ( 10, countDigits ( number) - numDigits );
return nuber / tmp;
}