C Programming what happens exactly with this recursive function - c

i have this function that when i start it prints only even numbers of the entered parameter can anyone explain to me what exactly happens in this function and how it ends up getting the even numbers
#include <stdio.h>
int what(int x){
if (x == 0)
return 0;
if (x % 2 == 0)
return what(x / 10) * 10 + x % 10;
return what(x / 10);
}
int main(){
printf("%d\n",what(145825));
return 0;
}
output
482

Here's what happens:
The what() function starts with the rightmost digit (= the whole number modulo 10) and then recurses into the rest of the digits by throwing away the rightmost digit (integer division by 10 throws away the right decimal digit).
If the right digit is even it is appended to the result of the recursion by multiplying it by 10 (making space for the extra digit on the right) and adding this digit (= the whole number modulo 10).
If the right digit is odd nothing is added to the result of the recursion.
Recursion stops when there are no more digits.
A good way to figure out to make recursion is to make a table that keeps track of what happens during each step, but of course a debugger is always the best way to really check what happens.
The following table is what happens each time what() is called:
x recursive x result even? returns
------ ----------- ------ ------- -------
145825 14582 482 - 482
______/ \_____________
/ \
14582 1458 48 48*10+2= 482
1458 145 4 4*10+8= 48
145 14 4 - 4
14 1 0 0*10+4= 4
1 0 0 - 0
0 - - - 0

Related

Recurrence relation for the algorithm

I have already given the following algorithm which I have to find the recurrence relation.
int Recursive(int n)
{
if(n<=1)
return n;
sum=0;
for(int j=0;j<n;j++)
sum++;
return Recursive(n/2) + Recursive(n/2) + sum;
}
I have obtained recurrence relation for the above algorithm as
T(n) = 2 T(n/2) + constant
But I am not sure about the constant part of this recurrence relation since we have sum in the algorithm. Just to clarify, sum is a global variable - the lack of declaration is not a typo.
Can anyone help me out to get the correct recurrence relation? Thanks.
Assumptions made in this answer:
sum is declared globally – since the apparently missing declaration is, as you stated, not a typo.
The question asks for the return value, not the time complexity.
The expressions in the return statement are evaluated in their order of appearance; this is not guaranteed by the C standard, so the answer is technically undefined.
Note that, since each call does either:
Returns its argument (if n <= 1)
Resets the value of sum to 0
... the function is guaranteed to be "closed", in the sense that its return value will only depend on its argument. It follows that:
The two separate calls to Recursive(n / 2) can be combined into just one call, without impacting the return value: return 2 * Recursive(n / 2) + sum;.
From this point on-wards is it assumed that this modification has been applied to the original code; this helps in clarifying the flow of the program, since there will now only be one path of execution (instead of branches created by two calls).
Now for the key part. The call to Recursive(n / 2) overwrites the value of sum before the function returns, undoing the work done by the preceding for-loop. This overwriting behavior continues down the recursion hierarchy, until the final call when the stopping condition n <= 1 is hit (it just returns n instead). It follows that:
There is only one value of sum which contributes to the final return value, given by its value after the penultimate call to Recursive.
Due to truncation by integer division, when the penultimate call is performed n is always 2 or 3 (both of which satisfy n / 2 = 1); these are thus also the possible final values of sum.
What values of n give sum = 2 and sum = 3 respectively? It is illustrative to consider the binary representation of n.
Integer division by 2 is equivalent to shifting the bit-pattern "right" by 1 (or "left" depending on endian-ness...), and discarding the least-significant bit. It follows that the final value of sum depends on only the 2 most significant bits of n:
initial bit-pattern >> penultimate call
-----------------------------------------
...000 10 xxx... ...0000 10 = 2
...000 11 xxx... ...0000 11 = 3
xxx: discarded bits
The bit-pattern of n has floor(log2(n)) + 1 significant bits; the final value of sum can therefore be compactly expressed as:
S(n) = 2 + second_most_significant_bit(n)
How many times is sum added to the return value? The number of recursive calls to Recursive (i.e. the total number of calls minus one, including the initial call, but excluding the final). This is given by floor(log2(n)):
Note that the return value of the final call will always be 1 if initially n >= 1. Therefore the final return value of Recursive is given by:
Test C code for confirmation:
// override the library definition of log2 to use integers only
int log2(int n) {
int b = 0;
while ((n >>= 1) != 0)
b++;
return b;
}
// get i-th bit from bit pattern of n
int get_bit(int n, int i) {
return (n >> (i - 1)) & 1;
}
// calculating return value of Recursive using equation above
int Value(int n) {
int l2n = log2(n); // floor(log2(n))
int p2l = 1 << l2n; // 2^(floor(log2(n)))
return p2l + (p2l - 1) * (2 + get_bit(n, l2n));
}
Results:
n | Recursive Value
-------------------------------
2 | 4 4
3 | 5 5
4 - 5 | 10 10
6 - 7 | 13 13
8 - 11 | 22 22
12 - 15 | 29 29
16 - 23 | 46 46
24 - 31 | 61 61
32 - 47 | 94 94
48 - 63 | 125 125
64 - 95 | 190 190
I am not sure about the constant part of this recurrence relation
There is no constant part, since sum equals n after the loop. This gives:
T(n) = 2T(n/2)+n
So if the sum is global variable, T(n) = 2T(n/2)+C(Constant) and if sum is local variable T(n) = 2T(n/2)+n . Am I correct?
No, as mch wrote:
It seems that sum is a global variable… In this case it would be unspecified if sum or one of the Recursive(n/2) will be evaluated first.
This means it would be unspecified whether T(n) = 2T(n/2)+n or T(n) = 2T(n/2)+n/2; in neither case there's a constant part.

regard C programming code and logic building

Atually i have i understand the code but doesn't understand the logic of the code.I know what is going on but i doesn't know what is happening.The code is of even or odd.The code is.
#include<stdio.h>
int main() {
int i;
for(i=1; i<26; i++) {
if(i%2==1)
printf("%d\n",i);
}
return 0;
}
output:
1
3
5
7
9
11
13
15
17
19
21
23
25.
1st repitition:-
(i=1;i<26;i++)
if(i%2==1)
1%2==1
but the result of 1%2 is 0.
I am still getting 1 on my screen. I don't know how I get this '1' , even 1 is
not equal to 0.
2nd repitition:-
(i=1;i<26;i++)
if(i%2==1)
now, at 2nd repition i is 2. AND (2%2) is equal to 0 and 0 is not equal to 1 as follows (0==1) and i am getting 3 on my output screen as i mention above on my screen.
Either I didn't use if condition. how i get this 3 and so on.
The modulo operator gives your the remainder after integer division. Integer division is different to standard (floating point) division.
1/2 = 0.5 (floating point division)
1\2 = 0 (integer division)
Integer Division
Integer division tells you the total number of times the second number 'fits' inside the first number. It's more obvious with a bigger example:
10/3 = 3.333 etc.
10\3 = 3
You cannot fit another entire 3 into 10.
Modulo (the complement of Integer Division)
Modulo tells you how much space you have left (the remainder). After you put three 3s into 10, you have 1 space left.
10%3 = 1 (i.e. 10-3*3)
If you used 11 instead of 10, you would have 2 spaces left. If you used 12, you could fit another whole 3 in, leaving no space left.
10\3=3 (with 1 space remaining)
11\3=3 (with 2 spaces remaining)
12\3=4
13\3=4 (with 1 space remaining)
Modulo gives you the amount of space remaining:
10%3=1
11%3=2
12%3=0
13%3=1
etc.
Modulo by 2 (to assess even/odd)
In your example, you're doing modulo 2. You cannot fit any whole 2s into 1.
1\2=0 (quotient)
1%2=1 (remainder)
So... In your loop:
i=1 > 1%2=1 > 1==1 (true) > print 1
i=2 > 2%2=0 > 0==1 (false) > do nothing
i=3 > 3%2=1 > 1==1 (true) > print 3
i=4 > 4%2=0 > 0==1 (true) > do nothing
Modulus operator % in this case returns 0 if the number is even and 1 if the number is odd. So, your code:
for(i=1; i<26; i++) {
if(i%2==1)
printf("%d\n",i);
}
checks if the number is odd, and if it is, prints it out. That's the logic behind the modulus operator.
I would suggest in later use to modify this code into:
for(i=1; i<26; i++) {
if(i%2!=0)
printf("%d\n",i);
}
to avoid mistakes with negative numbers.
Read this!
I don't know which part of the comments you didn't understand, but the gist is:
1%2 is NOT 0, but 1.
Either you accept that, and then the program's behavior should be clear, or you don't accept it, and then you did not understand what the % operator does. Go and read up on it.

Minimum base of a number which makes it a palindrome when represented in that base

Given an Integer x, I have to find a minimum baseb(b > 1) such that x base b is a palindrome.
Eg: 5 base 2 is a palindrome i.e. 5 in base 2 : 101 is a palindrome. How to solve it in a better way other than solving it brute-force?
Fair warning: this is not a complete answer, but some notes which may be useful. Hopefully given the unorthodox nature of the question and comments so far, no one will be too upset by this. :)
Base 2
11: 3
101: 5 (+2) d
111: 7 (+2) 2
1001: 9 (+2) d
1111: 15 (+6) 2
10001: 17 (+2) d
10101: 21 (+4)
11011: 27 (+6) 2
11111: 31 (+4)
100001: 33 (+2) d
101101: 45 (+12)
110011: 51 (+6) 2
111111: 63 (+12)
Base 3
11: 4
22: 8 (+4) 1
101: 10 (+2) d
111: 13 (+3)
121: 16 (+3)
202: 20 (+4) 1
212: 23 (+3)
222: 26 (+3)
1001: 28 (+2) d
1111: 40 (+12)
1221: 52 (+12)
2002: 56 (+4) 1
2112: 68 (+12)
2222: 80 (+12)
Base 4
11: 5
22: 10 (+5) 1
33: 15 (+5) 1
101: 17 (+2) d
111: 21 (+4)
121: 25 (+4)
131: 29 (+4)
202: 34 (+5) 1
212: 38 (+4)
222: 42 (+4)
232: 46 (+4)
303: 51 (+5) 1
313: 55 (+4)
323: 59 (+4)
333: 63 (+4)
I marked the difference from previous as (+n) and on the end added some notes:
1: the first digit incremented here
2: the second digit incremented here (I only marked this for base 2; it seemed irrelevant elsewhere)
d: the number of digits incremented here (and the first digit reset to 1)
Some structural observations:
The first (smallest) palindrome in a base is always (base+1). We don't allow 1, nor any leading zeros.
The first N palindromes for (N < base) are N*(base+1).
The (base)th palindrome is always 2 more than (base-1)th (and is always represented as 101).
The number of 2-digit palindromes is (base-1).
The number of 3- and 4-digit palindromes is (base-1)*base.
And finally, some less-developed ideas:
The number of digits of the palindrome representation of x is 1+log_base(x).
The first palindrome of a given length is always 10..01.
You can see patterns of repeating differences when there is no marker on the end (i.e. when the first digit and the count of digits are both unchanged). This may let us "fast forward" through the candidate palindromes starting from 10..01.
This has to be solved in a brute manner, but you can avoid making it a brute-force search by applying some logic to your approach, eliminating some of the candidates.
For example, you can avoid testing for bases which the number is divisible with, thus save a base conversion process as well as a palindrome test. The reason is simple: Representation in any base may not start with a zero, and this means that a number may not end with a zero in that representation as well, otherwise would not be a palindrome.
A number ending with a zero in a base x representation means that that number is divisible with x without a remainder.
This hint cannot be carried over to other digits, because rest could be anything that is representable in that base.
Unfortunately, I cannot come up with any other generalized logic to eliminate candidates. I can, however, come up with another one that will bring down the upper bound for bases to check for candidates, after which it can be surely said that the answer is simply base (x - 1) for that x.
Base (x - 1) for x produces 11 as the representation, which is a palindrome. As the bases decrease, either the digits in the representation become larger, or we get more digits.
The next-smallest palindrome in base 2 would be 101
The next-smallest palindrome in any base greater than 2 would be 22
Let's do the checking from reverse, start from top:
for (int base = x - 1; base >= 2; base--)
// is x represented palindromic at base (base)
Imagine this for a large x. The answer will be yes initially, then we will start having a no for a long while for sure. Why is that? Let me demonstrate:
/*
base representation
x - 1 11
x - 2 12
x - 3 13
x - 4 14
...
x - n 1n
...
x-x/2 20 or 21 for x even or odd
x / 2 20 or 21 for x even or odd
Until x / 2, the second digit (from last) will stay the same and the first one will increase slowly one by one.
It is similar for between x / 2 and x / 3, but the difference in between those two is way smaller (x / 6 compared to x / 2), as well as the first digit will start increasing two by two; therefore applying this logic to the rest becomes less and less significant.
Okay, for this reason, with the exception of numbers that are less than 6, if we happen to fail to find any base less than (x / 2) that yields a palindromic representation for a number x, we can safely give up and say that the answer is (x - 1).
All this text, explaining only two simple logics that can be implemented to prevent superfluous testing:
Do not check for bases that are proper divisors of the number
Short-cut to (x - 1) if checks exceed (x / 2) for numbers x greater than or equal to 6
One last discussion: If the subject is representation in different bases, why get limited by the letters in any alphabet? Especially when we're working on computers? Just use integer arrays, each element representing a digit properly with numbers and not with any letter or anything else. Just like in strings, a terminating value can be used and that could be -1. Probably a lot easier for a computer, since it won't have to convert things back and forth into letters anyway.
And here's a source code that does what I've explained above:
#include <stdio.h>
#include <malloc.h>
int ispalindrome(const int * string)
{
int length = 0;
while (string[length] != -1)
length++;
for (int i = 0; i < length / 2; i++)
{
if (string[i] != string[length - 1 - i])
return 0;
}
return 1;
}
int * converttobase(int number, int base)
{
int length = 0;
int temp = number;
while (temp)
{
length++;
temp /= base;
}
int * result = calloc(length + 1, sizeof * result);
for (int i = length - 1; i >= 0; i--)
{
result[i] = number % base;
number /= base;
}
result[length] = -1;
return result;
}
int lowestpalindromebase(int number)
{
int limit = (number < 6) ? (number + 2) : (number / 2);
// if number is more than or equal to 6, limit candidates with the half of it
// because, reasons...
for (int base = 2; base < limit; base++)
{
if (number % base) // number does have a remainder after division with base
{
int * converted = converttobase(number, base);
if (ispalindrome(converted))
{
free(converted);
return base;
}
free(converted);
}
}
return number - 1;
}
int main( )
{
for (int i = 1; i < 60; i++)
{
printf("%2d is palindromic at base %d\n", i, lowestpalindromebase(i));
}
return 0;
}
For posterity, here is a brute force approach, checking from 3 to 1000. You 'only' have to check bases from 2 to n-1, as logically n in base n-1 is always 11 -- the smallest possible base in which it's still a palindrome.
Strangely enough, only the numbers 3, 4, 6, 11, and 19 need checking all the way up to 11.
Up to 1000, there are 60 palindromes in binary, so these are found on the first try.
As can be expected, above base 36 it cannot find a palindrome for lots of numbers.
Two Three noteworthy recurring values:
any number n^2 + 1 in base n is 101.
any number n^2 in base n-1 is 121.
all results of 1[0*]1 seem to be for x^n+1.
int is_palindrome (char *string)
{
int l = strlen(string), l2 = (l+1)>>1, i = 0;
while (i < l2)
{
if (string[i] != string[l-1-i])
return 0;
i++;
}
return 1;
}
int main (void)
{
char buf[256];
int number, base, check;
int per_base[36] = { 0 };
for (number=3; number<=1000; number++)
{
check = 0;
for (base=2; base<=min(36,number-1); base++)
{
itoa (number, buf, base);
if (is_palindrome (buf))
{
check++;
per_base[base]++;
printf ("%d in base %d is %s\n", number, base, buf);
break;
}
}
if (!check)
printf ("%d is not a palindrome in anything up to 36\n", number);
}
for (number=2; number<36; number++)
printf ("%d-ary palindromes: %d\n", number, per_base[number]);
return 0;
}

Octal to Decimal multidigit in C

I have a program I am writing that converts Octal to Decimal numbers. Most of it works.
(more code above this, assume all variables are properly declared).
for(i; i > 0; i--)
{
decimalNumber = (decimalNumber + (number['i'] * pow(8,power)));
power++;
}
The code correctly shifts over to the right to do other digits but it doesn't change the number it is working with. For example, entering 54 in octal results in an output of 36, 4*(8^0) + 4*(8^1) when it should be outputting 4*(8^0) + 5*(8^1), or 44.
'i' is a constant. You probably meant just i. Also, << 3.
As Ignacio pointed out, 'i' is a constant and will cause you to access the same out of bounds array element on each iteration of the loop. Since I assume you start with i equal to the number of digits in the array (you didn't show that code), you want to subtract 1 from it when you use it as an array index.
You're traversing the string in the wrong direction.
Or, better, change your logic:
5 -> 5*8^0
54 -> (5*8^0)*8 + 4
543 -> ((5*8^0)*8 + 4)*8 + 3
number[0] is 5
number[1] is 4
decimalNumber is 0
power is 0
i = 1 downto 0 do
decimalNumber = (decimalNumber + (number[i:1,0] * pow(8,power:0,1)));
power++;
do end

How do I find the next multiple of 10 of any integer?

Dynamic integer will be any number from 0 to 150.
i.e. - number returns 41, need to return 50. If number is 10 need to return 10. Number is 1 need to return 10.
Was thinking I could use the ceiling function if I modify the integer as a decimal...? then use ceiling function, and put back to decimal?
Only thing is would also have to know if the number is 1, 2 or 3 digits (i.e. - 7 vs 94 vs 136)
Is there a better way to achieve this?
Thank You,
n + (10 - n % 10)
How this works. The % operator evaluates to the remainder of the division (so 41 % 10 evaluates to 1, while 45 % 10 evaluates to 5). Subtracting that from 10 evaluates to how much how much you need to reach the next multiple.
The only issue is that this will turn 40 into 50. If you don't want that, you would need to add a check to make sure it's not already a multiple of 10.
if (n % 10)
n = n + (10 - n % 10);
You can do this by performing integer division by 10 rounding up, and then multiplying the result by 10.
To divide A by B rounding up, add B - 1 to A and then divide it by B using "ordinary" integer division
Q = (A + B - 1) / B
So, for your specific problem the while thing together will look as follows
A = (A + 9) / 10 * 10
This will "snap" A to the next greater multiple of 10.
The need for the division and for the alignment comes up so often that normally in my programs I'd have macros for dividing [unsigned] integers with rounding up
#define UDIV_UP(a, b) (((a) + (b) - 1) / (b))
and for aligning an integer to the next boundary
#define ALIGN_UP(a, b) (UDIV_UP(a, b) * (b))
which would make the above look as
A = ALIGN_UP(A, 10);
P.S. I don't know whether you need this extended to negative numbers. If you do, care should be taken to do it properly, depending on what you need as the result.
What about ((n + 9) / 10) * 10 ?
Yields 0 => 0, 1 => 10, 8 => 10, 29 => 30, 30 => 30, 31 => 40
tl;dr: ((n + 9) / 10) * 10 compiles to the nicest (fastest) asm code in more cases, and is easy to read and understand for people that know what integer division does in C. It's a fairly common idiom.
I haven't investigated what the best option is for something that needs to work with negative n, since you might want to round away from zero, instead of still towards +Infinity, depending on the application.
Looking at the C operations used by the different suggestions, the most light-weight is Mark Dickinson's (in comments):
(n+9) - ((n+9)%10)
It looks more efficient than the straightforward divide / multiply suggested by a couple people (including #bta): ((n + 9) / 10) * 10, because it just has an add instead of a multiply. (n+9 is a common subexpression that only has to be computed once.)
It turns out that both compile to literally identical code, using the compiler trick of converting division by a constant into a multiply and shift, see this Q&A for how it works. Unlike a hardware div instruction that costs the same whether you use the quotient, remainder, or both results, the mul/shift method takes extra steps to get the remainder. So the compiler see that it can get the same result from a cheaper calculation, and ends up compiling both functions to the same code.
This is true on x86, ppc, and ARM, and all the other architectures I've looked at on the Godbolt compiler explorer. In the first version of this answer, I saw an sdiv for the %10 on Godbolt's gcc4.8 for ARM64, but it's no longer installed (perhaps because it was misconfigured?) ARM64 gcc5.4 doesn't do that.
Godbolt has MSVC (CL) installed now, and some of these functions compile differently, but I haven't taken the time to see which compile better.
Note that in the gcc output for x86, multiply by 10 is done cheaply with lea eax, [rdx + rdx*4] to do n*5, then add eax,eax to double that. imul eax, edx, 10 would have 1 cycle higher latency on Intel Haswell, but be shorter (one less uop). gcc / clang don't use it even with -Os -mtune=haswell :/
The accepted answer (n + 10 - n % 10) is even cheaper to compute: n+10 can happen in parallel with n%10, so the dependency chain is one step shorter. It compiles to one fewer instruction.
However, it gives the wrong answer for multiples of 10: e.g. 10 -> 20. The suggested fix uses an if(n%10) to decide whether to do anything. This compiles into a cmov, so it's longer and worse than #Bta's code. If you're going to use a conditional, do it to get sane results for negative inputs.
Here's how all the suggested answers behave, including for negative inputs:
./a.out | awk -v fmt='\t%4s' '{ for(i=1;i<=NF;i++){ a[i]=a[i] sprintf(fmt, $i); } } END { for (i in a) print a[i]; }'
i -22 -21 -20 -19 -18 -12 -11 -10 -9 -8 -2 -1 0 1 2 8 9 10 11 12 18 19 20 21 22
mark -10 -10 -10 -10 0 0 0 0 0 0 0 0 0 10 10 10 10 10 20 20 20 20 20 30 30
igna -10 -10 -10 0 0 0 0 0 10 10 10 10 10 10 10 10 10 20 20 20 20 20 30 30 30
utaal -20 -20 -20 -10 -10 -10 -10 -10 0 0 0 0 0 10 10 10 10 10 20 20 20 20 20 30 30
bta -10 -10 -10 -10 0 0 0 0 0 10 10 10 10 10 10 10 10 10 20 20 20 20 20 30 30
klatchko -10 -10 -10 -10 0 0 0 0 0 0 0 0 0 10 10 10 10 10 20 20 20 20 20 30 30
branch -10 -10 -20 0 0 0 0 -10 10 10 10 10 0 10 10 10 10 10 20 20 20 20 20 30 30
(transpose awk program)
Ignacio's n + (((9 - (n % 10)) + 1) % 10) works "correctly" for negative integers, rounding towards +Infinity, but is much more expensive to compute. It requires two modulo operations, so it's essentially twice as expensive. It compiles to about twice as many x86 instructions, doing about twice the work of the other expressions.
Result-printing program (same as the godbolt links above)
#include <stdio.h>
#include <stdlib.h>
int f_mark(int n) { return (n+9) - ((n+9)%10); } // good
int f_bta(int n) { return ((n + 9) / 10) * 10; } // compiles to literally identical code
int f_klatchko(int n) { return n + 10 - n % 10; } // wrong, needs a branch to avoid changing multiples of 10
int f_ignacio(int n) { return n + (((9 - (n % 10)) + 1) % 10); } // slow, but works for negative
int roundup10_utaal(int n) { return ((n - 1) / 10 + 1) * 10; }
int f_branch(int n) { if (n % 10) n += (10 - n % 10); return n; } // gcc uses cmov after f_accepted code
int main(int argc, char**argv)
{
puts("i\tmark\tigna\tutaal\tbta\tklatch\tbranch");
for (int i=-25 ; i<25 ; i++)
if (abs(i%10) <= 2 || 10 - abs(i%10) <= 2) // only sample near interesting points
printf("%d\t%d\t%d\t%d\t%d\t%d\t%d\n", i, f_mark(i), f_accepted(i),
f_ignacio(i), roundup10_utaal(i), f_bta(i), f_branch(i));
}
How about using integer math:
N=41
N+=9 // Add 9 first to ensure rounding.
N/=10 // Drops the ones place
N*=10 // Puts the ones place back with a zero
in C, one-liner:
int inline roundup10(int n) {
return ((n - 1) / 10 + 1) * 10;
}
Be aware that answers based on the div and mod operators ("/" and "%") will not work for negative numbers without an if-test, because C and C++ implement those operators incorrectly for negative numbers. (-3 mod 5) is 2, but C and C++ calculate (-3 % 5) as -3.
You can define your own div and mod functions. For example,
int mod(int x, int y) {
// Assert y > 0
int ret = x % y;
if(ret < 0) {
ret += y;
}
return ret;
}
n + (((9 - (n % 10)) + 1) % 10)
You could do the number mod 10. Then take that result subtract it from ten. Then add that result to the original.
if N%10 != 0 #added to account for multiples of ten
a=N%10
N+=10-a
int n,res;
...
res = n%10 ? n+10-(n%10) : n;
or
res = (n / 10)*10 + ((n % 10) ? 10:0);
In pseudo code:
number = number / 10
number = ceil(number)
number = number * 10
In Python:
import math
def my_func(x):
return math.ceil(x / 10) * 10
That should do it. Keep in mind that the above code will cast an integer to a float/double for the arithmetic, and it can be changed back to an integer for the final return. Here's an example with explicit typecasting
In Python (with typecasting):
import math
def my_func(x):
return int(math.ceil(float(x) / 10) * 10)
round_up(int i)
{
while(i%10) {
i++;
}
return(i);
}

Resources