I have a range of numbers from 100 to 999. I need to get every number separately of it and check whether it can be divided by 2. For example:
232
2 divided by 2 = 1 = true
3 divided by 2 = 1.5 = false
2 divided by 2 = 1 = true
and so on.
To get the first number all I have to do is to divide the entire number by 100.
int x = 256;
int k = x/100;
so x would hold a value of 2.
Now, is there a way to check those other ones? Because k = x/10; would already be 25.
Try this:
int x = 256;
int i = x / 100; // i is 2
int j = (x % 100) / 10; // j is 5
int k = (x % 10); // k is 6
maybe look into integer division and the modulo.
int k1 = (x / 10) % 10 // "10s"
int k2 = ( x / 100 ) % 10 // "100s"
//etc etc
Use modulo to get the last digit of the number, then divide by ten to discard the last digit.
Repeat while the number is non-zero.
What you need is the modulus operator %. It does a division and returns the reminder.
1 % 2 = 1
2 % 2 = 0
3 % 2 = 1
4 % 2 = 0
...
eg. take 232:
int num = 232;
int at_ones_place = num % 10;
int at_tens_place = ( num /10 ) % 10 ;
int at_hundreds_place = (num /100);
Related
I need a branchless number cycle code.
like this:
int i = 0;
i = (i + 1) % 4 //1
i = (i + 1) % 4 //2
i = (i + 1) % 4 //3
i = (i + 1) % 4 //0
i = (i + 1) % 4 //1
...
But it should work in the reverse order of the code above. (3 > 2 > 1 > 0 > 3 > ...)
I first tried "i = (i - 1) % 4".
But this worked differently than I wanted. (-1 > -2 > -3 > 0 > -1 > ...)
However, if I use the method of adding 4 when i is negative, this code is no longer branchless.
How can I implement the functionality which I want (without additional variables or arrays)?
(This article has been translated by Google Translate.)
The error happens because in C89 the remainder of negative numbers was underspecified and from C99, negative % positive will result in a negative number which is unlike in some programming languages such as Python, where (-1) % 4 would indeed result in 3.
But it is easy to circumvent. When you subtract 1, it is the same as adding -1. Since 0 - 1 will get to -1, we would have a negative remainder. To stay positive, instead of adding the negative -1 we can add a positive number that's congruent to -1 (mod m). The smallest positive such number is m - 1 for an m > 1. Therefore we can use:
#define MODULUS 4 // or any other moduli > 1
int i = 0;
i = (i + (MODULUS - 1)) % MODULUS; //3
i = (i + (MODULUS - 1)) % MODULUS; //2
i = (i + (MODULUS - 1)) % MODULUS; //1
i = (i + (MODULUS - 1)) % MODULUS; //0
i = (i + (MODULUS - 1)) % MODULUS; //3
You need to change your expression a bit. It should be:
i = ( i + 3 ) % 4;
In general, if you want a number in range [0,N-1] with such cycle then the equation should be:
i = (i + (N - 1)) % N;
You can see it working here(manually several times) and here (in loop):
int main()
{
int i = 0;
i = ( i + 3 ) % 4; //3
i = ( i + 3 ) % 4; //2
i = ( i + 3 ) % 4; //1
i = ( i + 3 ) % 4; //0
i = ( i + 3 ) % 4; //3
i = ( i + 3 ) % 4; //2
i = ( i + 3 ) % 4; //1
i = ( i + 3 ) % 4; //0
return 0;
}
You can use unsigned arithmetic, then the numbers won't become negative.
unsigned i = 0;
i = (i - 1) % 4 //3
i = (i - 1) % 4 //2
i = (i - 1) % 4 //1
i = (i - 1) % 4 //0
i = (i - 1) % 4 //3
Also, maybe more intuitive, you can use bitwise operations to implement a 2-bit counter.
unsigned i = 0;
i = (i - 1) & 3;
i = (i - 1) & 3;
i = (i - 1) & 3;
i = (i - 1) & 3;
i = (i - 1) & 3;
On machine code level, this is identical to the code above.
There are two cases:
Case 1: The modulo is a power of 2
In this case, you can simply use unsigned arithmetic with a bit mask:
unsigned i = ...;
i = (i - 1) & (modulo - 1);
When i = 0, subtracting 1 will yield a value with all bits set in unsigned arithmetic, and the mask operation & will yield the value modulo - 1.
Case 2: The modulo is not a power of 2
In this case, no fancy bit tricks work. You can only avoid going negative:
i = (i + modulo - 1) % modulo;
It is my understanding that rand() % a + b will return numbers between a and b including both a and b. I must be misunderstanding this though, because when I run the code below int r will return 2, 3, or 4. I, of course, am expecting it to return 2 or 3. I'm calling srand(time(NULL)); in main and I'm using
#include <time.h> and #include <stdlib.h>
Am I missing something?
int r = (rand() % 3) + 2;
if (r ==2)
g_fan.draw(r); // skin == 2
else
g_fan.draw(1 + r); //skin == 4
It is my understanding that rand() % a + b will return numbers between a and b including both a and b.
No. It will result in a number between b and (a+b-1), both including.
Range of values of rand() % a is 0 and a-1, both including.
Hence, the range of values of rand() % a + b is b and (a-1+b), both including.
To get random values between a and b, both including, use:
auto interval = (b-a+1);
auto result = a + rand() % interval;
let num be any number you get by calling rand() and if you do % with 3 , there is a possibility of getting one of these number 0, 1, 2.
therefore you are getting 2 ,3, 4 for :
int r = (rand() % 3) + 2;
int r = (rand() % 3) + 2;
The rand() % 3 will return a number between 0 and 2. When you add t2 to each number, that means it will return 2 to 4. The rand() % afunction in general returns a value form 0 to a - 1. When you do rand() % a + b, then the resulting value will range from 0 + b to a - 1 + b.
To get a value between 2 and 3, use:
int r = (rand() % 2) + 2;
The folloing rand() function gives a number from 0 to 2 - 1, which is 1. When you add 2 to each number, you get a range of 0 + 2, which is 2, to 2 - 1 + 2, which is 3.
I am new to coding and I am finding this site really helpful. So I have been trying to solve this problem and I am getting erroneous results, so I would be really grateful if you could help me out here.
The Problem: Find the sum of all the multiples of 3 or 5 below 1000. (For example, if we list all the positive integers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9, which sum is 23.)
My code:
count = 0
count1 = 0
for x in range(1000):
if x % 5 == 0:
count = count + x
if x % 3 == 0:
count1 = count1 + x
print count1 + count
What am I doing wrong?
Thanks in advance!
You want an elif in your code so you don't count the same x twice but a simpler way is to use an or with a single count variable:
count = 0
for x in range(1000):
if x % 5 == 0 or x % 3 == 0:
count += x
Which can be done using sum:
print(sum(x for x in range(3, 1000) if not x % 5 or not x % 3))
For completeness, a working version using your own code:
count = 0
count1 = 0
for x in range(1000):
if x % 5 == 0:
count += x
elif x % 3 == 0:
count1 += x
print count1 + count
ifs are always evaluated; so, for instance, when x is 15 it is evenly divisible by 5 and 3 so you count 15 twice, an elif is only evaluated if the previous if/elif evaluates to False so using elif only one occurrence of x will be added to the total.
Below 10 there is no number being multiple of both 5 and 3. But below 1000 there are several numbers divided exactly by 3 and 5 also (15, 45 ...).
So you need:
count=0
for x in range(1000):
if x % 5 == 0 or x % 3 == 0:
count=count + x
print count
int sum_down(int x)
{
if (x >= 0)
{
x = x - 1;
int y = x + sum_down(x);
return y + sum_down(x);
}
else
{
return 1;
}
}
What is this smallest integer value of the parameter x, so that the returned value is greater than 1.000.000 ?
Right now I am just doing it by trial and error and since this question is asked via a paper format. I don't think I will have enough time to do trial and error. Question is, how do you guys visualise this quickly such that it can be solved easily. Thanks guys and I am new to programming so thanks in advance!
The recursion logic:
x = x - 1;
int y = x + sum_down(x);
return y + sum_down(x);
can be simplified to:
x = x - 1;
int y = x + sum_down(x) + sum_down(x);
return y;
which can be simplified to:
int y = (x-1) + sum_down(x-1) + sum_down(x-1);
return y;
which can be simplified to:
return (x-1) + 2*sum_down(x-1);
Put in mathematical form,
f(N) = (N-1) + 2*f(N-1)
with the recursion terminating when N is -1. f(-1) = 1.
Hence,
f(0) = -1 + 2*1 = 1
f(1) = 0 + 2*1 = 2
f(2) = 1 + 2*2 = 5
...
f(18) = 17 + 2*f(17) = 524269
f(19) = 18 + 2*524269 = 1048556
Your program can be written this way (sorry about c#):
public static void Main()
{
int i = 0;
int j = 0;
do
{
i++;
j = sum_down(i);
Console.Out.WriteLine("j:" + j);
} while (j < 1000000);
Console.Out.WriteLine("i:" + i);
}
static int sum_down(int x)
{
if (x >= 0)
{
return x - 1 + 2 * sum_down(x - 1);
}
else
{
return 1;
}
}
So at first iteration you'll get 2, then 5, then 12... So you can neglect the x-1 part since it'll stay little compared to the multiplication.
So we have:
i = 1 => sum_down ~= 4 (real is 2)
i = 2 => sum_down ~= 8 (real is 5)
i = 3 => sum_down ~= 16 (real is 12)
i = 4 => sum_down ~= 32 (real is 27)
i = 5 => sum_down ~= 64 (real is 58)
So we can say that sum_down(x) ~= 2^x+1. Then it's just basic math with 2^x+1 < 1 000 000 which is 19.
A bit late, but it's not that hard to get an exact non-recursive formula.
Write it up mathematically, as explained in other answers already:
f(-1) = 1
f(x) = 2*f(x-1) + x-1
This is the same as
f(-1) = 1
f(x+1) = 2*f(x) + x
(just switched from x and x-1 to x+1 and x, difference 1 in both cases)
The first few x and f(x) are:
x: -1 0 1 2 3 4
f(x): 1 1 2 5 12 27
And while there are many arbitrary complicated ways to transform this into a non-recursive formula, with easy ones it often helps to write up what the difference is between each two elements:
x: -1 0 1 2 3 4
f(x): 1 1 2 5 12 27
0 1 3 7 15
So, for some x
f(x+1) - f(x) = 2^(x+1) - 1
f(x+2) - f(x) = (f(x+2) - f(x+1)) + (f(x+1) - f(x)) = 2^(x+2) + 2^(x+1) - 2
f(x+n) - f(x) = sum[0<=i<n](2^(x+1+i)) - n
With eg. a x=0 inserted, to make f(x+n) to f(n):
f(x+n) - f(x) = sum[0<=i<n](2^(x+1+i)) - n
f(0+n) - f(0) = sum[0<=i<n](2^(0+1+i)) - n
f(n) - 1 = sum[0<=i<n](2^(i+1)) - n
f(n) = sum[0<=i<n](2^(i+1)) - n + 1
f(n) = sum[0<i<=n](2^i) - n + 1
f(n) = (2^(n+1) - 2) - n + 1
f(n) = 2^(n+1) - n - 1
No recursion anymore.
How about this :
int x = 0;
while (sum_down(x) <= 1000000)
{
x++;
}
The loop increments x until the result of sum_down(x) is superior to 1.000.000.
Edit : The result would be 19.
While trying to understand and simplify the recursion logic behind the sum_down() function is enlightening and informative, this snippet tend to be logical and pragmatic in that it does not try and solve the problem in terms of context, but in terms of results.
Two lines of Python code to answer your question:
>>> from itertools import * # no code but needed for dropwhile() and count()
Define the recursive function (See R Sahu's answer)
>>> f = lambda x: 1 if x<0 else (x-1) + 2*f(x-1)
Then use the dropwhile() function to remove elements from the list [0, 1, 2, 3, ....] for which f(x)<=1000000, resulting in a list of integers for which f(x) > 1000000. Note: count() returns an infinite "list" of [0, 1, 2, ....]
The dropwhile() function returns a Python generator so we use next() to get the first value of the list:
>>> next(dropwhile(lambda x: f(x)<=1000000, count()))
19
consider that
0 -- is the first
1 -- is the second
2 -- is the third
.....
9 -- is the 10th
11 -- is the 11th
what is an efficient algorithm to find the nth palindromic number?
I'm assuming that 0110 is not a palindrome, as it is 110.
I could spend a lot of words on describing, but this table should be enough:
#Digits #Pal. Notes
0 1 "0" only
1 9 x with x = 1..9
2 9 xx with x = 1..9
3 90 xyx with xy = 10..99 (in other words: x = 1..9, y = 0..9)
4 90 xyyx with xy = 10..99
5 900 xyzyx with xyz = 100..999
6 900 and so on...
The (nonzero) palindromes with even number of digits start at p(11) = 11, p(110) = 1001, p(1100) = 100'001,.... They are constructed by taking the index n - 10^L, where L=floor(log10(n)), and append the reversal of this number: p(1101) = 101|101, p(1102) = 102|201, ..., p(1999) = 999|999, etc. This case must be considered for indices n >= 1.1*10^L but n < 2*10^L.
When n >= 2*10^L, we get the palindromes with odd number of digits, which start with p(2) = 1, p(20) = 101, p(200) = 10001 etc., and can be constructed the same way, using again n - 10^L with L=floor(log10(n)), and appending the reversal of that number, now without its last digit: p(21) = 11|1, p(22) = 12|1, ..., p(99) = 89|8, ....
When n < 1.1*10^L, subtract 1 from L to be in the correct setting with n >= 2*10^L for the case of an odd number of digits.
This yields the simple algorithm:
p(n) = { L = logint(n,10);
P = 10^(L - [1 < n < 1.1*10^L]); /* avoid exponent -1 for n=1 */
n -= P;
RETURN( n * 10^L + reverse( n \ 10^[n >= P] ))
}
where [...] is 1 if ... is true, 0 else, and \ is integer division.
(The expression n \ 10^[...] is equivalent to: if ... then n\10 else n.)
(I added the condition n > 1 in the exponent to avoid P = 10^(-1) for n=0. If you use integer types, you don't need this. Another choice it to put max(...,0) as exponent in P, or use if n=1 then return(0) right at the start. Also notice that you don't need L after assigning P, so you could use the same variable for both.)