The problem: user inputs two numbers: a big one, and a small one.
The small number is the number of digits from the last digit that will transfer into the front, and the remaining numbers will follow.
For example: if the big number is 456789 and the small one is 3, the result will be: 789456.
my idea was as follows:
if(...) {
newNum = BigNumber%(10*SmallNumber);
printf("%d", remainder");
SmallNumber--;
}
but it doesn't print in the order I was hoping for, digit by digit, and I can't understand why.
If using arrays would be allowed, it was no problem. Also I'm not allowed to use string.length, which also make it lots easier.
Rotating a number can be performed as a combination of cuts, shifts, and additions. For example, if you have a number 123456789 and you need to rotate it by 3, you can do it as follows:
Cut off the last three digits 123456789
Shift the remaining number by three digits to make 123456789
Shift the last three digits by six to make 789000000
Add the two numbers together 789000000 + 123456 to get the result 789123456.
Here is how you do these operations on decimal numbers:
Cutting off the last k digits is done with modulo % 10k
Shifting right by k digits is equivalent to integer division by 10k
Shifting left by k digits is equivalent to multiplication by 10k
Figuring out the number of significant digits in a number can be done by repeated integer division by ten.
Addition is done the usual way.
I think below code would help you -
//Here size = number of digits in bignumber-1
while(smallnumber--) {
temp = (bignumber - bignumber%pow(10,size))/(pow(10,size);
bignumber = bignumber%pow(10,size);
bignumber = bignumber*10 + temp;
}
Try this version:
#include <stdio.h>
#include <math.h>
int main(void)
{
long int num = 34234239;
int swap = 5, other;
long int rem = num % (int)(pow(10,swap)); /*The part that is shifted*/
other = log10(num-rem)+1-swap; /*Length of the other part*/
/* Result = (part to shift)*(Other part's length) + (Other part)*(Shifts) */
num = rem*(int)pow(10,other) + (num-rem)/(int)pow(10,swap);
printf("%ld\n",num);
return 0;
}
Related
The below code that works perfectly fine for smaller digits, But Time dilation for greater digits
given me the suggestion
#include<stdio.h>
int main()
{
int num;
int sum=0;
scanf("%d",&num);
for(int i=1;i<=num;i++)
{
if(i%3==0 || i%5==0)
sum += i;
}
printf("%d",sum);
}
Need efficient code for this
Try to reduce the time take for the code.
The answer can be computed with simple arithmetic without any iteration. Many Project Euler questions are intended to make you think about clever ways to find solutions without just using the raw power of computers to chug through calculations. (This was Project Euler question 1, except the Project Euler problem specifies the limit using less than instead of less than or equal to.)
Given positive integers N and F, the number of positive multiples of F that are less than or equal to N is ⌊N/F⌋. (⌊x⌋ is the greatest integer not greater than x.) For example, the number of multiples of 5 less than or equal to 999 is ⌊999/5⌋ = ⌊199.8⌋ = 199.
Let n be this number of multiples, ⌊N/F⌋.
The first multiple is F and the last multiple is n•F. For example, with 1000 and 5, the first multiple is 5 and the last multiple is 200•5 = 1000.
The multiples are evenly spaced, so the average of all of them equals the average of the first and the last, so it is (F + nF)/2.
The total of the multiples equals their average multiplied by the number of them, so the total of the multiples of F less than N is n • (F + n•F)/2.
Adding the sum of multiples of 3 and the sum of multiples of 5 includes the multiples of both 3 and 5 twice. We can correct for this by subtracting the sum of those numbers. Multiples of both 3 and 5 are multiples of 15.
Thus, we can compute the requested sum using simple arithmetic without any iteration:
#include <stdio.h>
static long SumOfMultiples(long N, long F)
{
long NumberOfMultiples = N / F;
long FirstMultiple = F;
long LastMultiple = NumberOfMultiples * F;
return NumberOfMultiples * (FirstMultiple + LastMultiple) / 2;
}
int main(void)
{
long N = 1000;
long Sum = SumOfMultiples(N, 3) + SumOfMultiples(N, 5) - SumOfMultiples(N, 3*5);
printf("%ld\n", Sum);
}
As you do other Project Euler questions, you should look for similar ideas.
I'm working on a code to verify valid credit card numbers. I'll be using the Luhn algorithm logic eventually, But first I'm trying to store the single digits of the card number into an array of size 20. Since there is no way to split an integer (integer here is the credit card number) I thought of getting the remainder of the integer by dividing by 10 (This way I can get the individual digits). However, my problem is that when the size of the integer becomes 11 or more, only a few digits are getting stored and with the wrong values. I just started to learn C programming and would really appreciate it if someone could help me, Thank you.
Note: I have given -1 to the 0th index of the array to say that it's the end of the card number.
eg: 123467321234-1
Code :
#include <stdio.h>
int main() {
long int cardNo[20];
long int input_cardNo;
int cardNo[0] = -1; //card number ends here
int i = 1;
printf("Enter your card number : ");
scanf("%d", &input_cardNo);
do {
long int remainder = input_cardNo % 10; //getting the remainder of card number
long int division = input_cardNo / 10; //getting the div value of card number
cardNo[i] = remainder; //assigning the remainder value to an [i] index in the array
printf("%d\n", cardNo[i]);
input_cardNo = division; //updating the card number with the div vale
i++;
} while (input_cardNo != 0);
return 0;
}
Just a brief explanation why long int does not work.
For most operating systems long int stores have the same capacity as int, it stores from -2^31 to 2^31 - 1. See: Long Vs. Int C/C++ - What's The Point?
With this, the maximum value is: 2147483648 or around 9-10 digits for your case. You may use long long int to store up to 4.611686e+18 or 17-18 digits.
I plan to use this inside a game loop to draw the score using custom bitmap font.
Here is what I have. Now I know that I have used the modulus, division and power operators a bunch of times. I understand that using this in a game loop is not a good thing to do. Any suggestions?
// Get digit n, where n is digit starting from the units place and moving left
int getDigit(int number, int position)
{
return (number % (int)pow(10, position)) / pow(10, (position - 1));
}
If int is 32 bits, then:
static const int table[] =
{ 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 };
return number / table[position-1] % 10;
is a reasonable implementation:
It does not invoke pow or use floating-point arithmetic.
It uses one table look-up, one division by a variable, and one remainder operation with a constant (which a compiler can optimize to a multiplication and some shifts and adds).
(Note that position is adjusted in the table lookup to be one-based to match the code in the question, but common practice would be to call the units position position 0 instead of position 1.)
If digits are to be extracted for multiple positions or the whole number, then other implementations should be considered.
You said that you extract a digit in order to display the game score; so I assume you will use the whole original number.
You can extract all the digits in a loop this way:
int number = 1234; // this variable will be consumed
while (number) {
rightmostdigit = number % 10;
// do something with the extracted digit
number /= 10; // discard the rightmost at go to the next
}
The above routine extracts digits from the right, so the score shall be drawn from right to left. Warning that if the number is zero, the loop is never executed...
If you want to extract from left, and supposing a fixed-length score (like "00123"), you can store the single digits in an array, then read them back in the inverse direction: it should be faster than trying to extract the digits from left to right.
I'm trying to a create an algorithm that can convert base 10 numbers into base n numbers, where n is at most 10. However, for some weird reason the following algorithm in C fails at certain critical points for each base. For example, for base 2 and base 3 conversions, all numbers up to and including 1023 and 52,487 work, respectively, but numbers beyond that produce some weird negative result. I can't figure out why this is happening; can anyone help me?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int returnint;
int baseconvert(int number,int base) {
if(number == 0 || base == 10) {
return returnint;
}
returnint = (number % base) + (10 * baseconvert(number / base, base));
return returnint;
}
int main() {
fprintf(stdout,"%d\n",baseconvert(1023,2));
fprintf(stdout,"%d\n",baseconvert(52487,3));
}
EDIT:
Here is the printed result of the above print statements, if that's helpful:
1410065408
-2094967296
Your algorithm is very limited in the range of numbers vs. bases. The smaller the base is the more digits are needed to represent it. And since you store the result in decimal form, you'll waste your available data range very quickly. There is no fundamental data type that can hold the results for all the possible inputs. E.g., maximal 31-bit decimal number (normal integer, dropping the sign bit) will result in 31-digit output!
You have several options to cope with this:
Allocate a stack large enough and push the digits into it. Upon completion, print the stack contents.
Print the digits immediately without saving, this will eliminate the need to allocate anything.
E.g.:
#include <stdio.h>
void baseconvert(int number,int base)
{
if(number > 0)
{
int digit = (number % base);
baseconvert(number / base, base);
printf("%d",digit);
}
else
{
printf("\n");
}
}
int main()
{
baseconvert(1023,2);
baseconvert(52487,3);
}
It appears that the integer value is overflowing. For example, the decimal value 1023 in base two is 1111111111. If it is a 4 byte integer, then it will overflow when trying to "add" one more digit (the max signed integer in this case being 2147483647).
Since it appears your goal is to display a number in a different base, it might make more sense to store the digits in a character array.
On all processors that I know of, integers are already stored in binary form; this implies base 2. This value can be displayed in whatever base you desire, with some work on your part. printf() and friends allow you to easily print in base 10 (%d) and base 16 (%x). It is not difficult to imagine a method that would convert a binary (base 2) integer value into a character representation in base n.
I seriously doubt that you really intend to change the actual value of the integer, as you are doing. Like #ThoAppelsin said above, the number of apples in the bag stays the same, regardless of which base you choose for display.
By simply creating a method that represents (with digits) the integer in any base, you will also solve your overflow problem!
Your result is overflowing the integer range. Try using strings instead. This is the pseudocode which relies on strings to represent numbers and it can convert numbers from any base to any other base between 2 and 36 inclusive (using digits and upper case letters):
function ConvertNumber(number, b, d)
begin
newNumber = ""
while number <> "0"
begin
number = Divide(number, b, d, out remainder)
newDigit = ValueToDigit(remainder)
newNumber = Concatenate(newDigit, newNumber)
end
if newNumber ="" then
newNumber = "0"
end
function Divide(number, base, divisor, out remainder)
begin
remainder = 0
result = ""
for i = 0 to Length(number) - 1
begin
digitValue = DigitToValue(number[i])
remainder = base * remainder + digitValue
newDigitValue = remainder / divisor -- integer division
remainder = remainder mod divisor
if newDigitValue > 0 OR result <> "" then
newDigit = ValueToDigit(newDigitValue)
result = Concatenate(result, newDigit)
end
if result = "" then
result = "0"
return result
end
You can find the whole math and implementation in this article: Converting Number Bases.
I have int x = 346.
I need to get in turn, each time a new digit of it, so first 3, then 4, then 6.
Using floor does not help me here,
and other examples here give only the left/right digit.
Is there a simple algorithm?
a%10 gives you the last digit of a number i.e. its remainder when divided by 10. You can print all the digits of a number like so:
void print_digits(int a) {
while (a > 0) {
printf("%d\n", a%10);
a /= 10;
}
}
This will print the digits from least significant to most significant. You can get them in reverse order if you use an auxiliary stack for instance.