largest number without conditional operator - c

can any one please elaborate how to find largest of four numbers without using conditional operator.for 3 numbers i have done but for four numbers how to write different comparisons.

There is a standard way to compute min or max in 2's complement arithmetics without using conditionals:
int max(int a, int b){
unsigned diff = b - a; // negative if a > b
int sign = -(diff >> (sizeof(int) * CHAR_BIT - 1)); // -1 if a > b, 0 otherwise
return (a & sign) | (b & ~sign);
}
it can be easily scaled.

void main()
{
int a, b;
printf("Enter a and b:");
scanf("%d %d", &a, &b);
printf("Maximum number is %d", max(a, b));
getch();
}
int max(int a, int b)
{
int c, temp;
c = a - b;
temp = c + abs(c);
// To check if the difference is negative or not
if(temp) //As suggested by R..
return b;
else
return a;
}
This code is for compare two numbers. Make this comparison for all numbers.

you can find max of two number a,b by using following trick:
(abs(a+b)+abs(a-b))/2
Extend the trick for as many numbers you want.

Related

the programme codes of language c about input and output are wrong,could somebody help me find the fault?

I have the following code in c
#include <stdio.h>
int main(void)
{
int a, b, c, sum;
double d, p;
sum = a + b + c;
printf("请输入三个整数:");
scanf("%d %d %d", &a, &b, &c);
d = sum / 3;
printf("3个整数的平均值是:d=%.2f", d);
p = a / sum * 100;
printf(",第一个数占和的比例是:p=%4.2f%%", p);
}
It is about entering three integers from the keyboard, average them, and calculate the ratio of the first number to the sum of the three numbers. The output result retains 2 decimal places .
I cannot find where is wrong.
The two main issues are:
You calculate sum with uninitialized values for a, b and c. Move that calculation to after a successful scanf() to ensure those variables are set.
You probably want to do the calculations of d and p with double, rather than integer, precision. I make use of automatic type conversion via fractional constants. The other two options are to change the type of sum from an int to a double, or explicitly use a type cast (see answer by #FeihuLiu).
Minor issues:
Original code was formatted poorly (since fixed by one of our friends :-).
Optional for main() but it's a good idea to return an integer as your declaration said you would.
(not fixed) If you don't use p or d for anything else, consider just eliminating them in favor of doing the calculation call to printf()
It's generally a good idea to reduce the scope of variables so I moved those definitions to just before they are used.
#include <stdio.h>
int main(void) {
printf("请输入三个整数:");
int a, b, c;
if (scanf("%d %d %d", &a, &b, &c) != 3) {
// TBD: translate error message
printf("scanf failed\n");
return 1;
}
int sum = a + b + c;
double d = sum / 3.0;
printf("3个整数的平均值是:d=%.2f", );
double p = 100.0 * a / sum;
printf(",第一个数占和的比例是:p=%4.2f%%", p);
return 0;
}
Besides the sum problem, integer division will result in integer. You can use the following code:
#include <stdio.h>
int main(void) {
int a, b, c, sum;
double d, p;
printf("请输入三个整数:");
scanf("%d %d %d", &a, &b, &c);
sum = a + b + c;
d = (double) sum / 3;
printf("3个整数的平均值是:d=%.2f", d);
p = (double) a / sum * 100;
printf(",第一个数占和的比例是:p=%4.2f%%", p);
}

How to combine 2 integers in order to get 1?

I searched about this but I didn't find a clear answer for this problem in C language.
Imagine that I have an int a = 123 and another int b = 456.
How do I combine them in order to get combine(a, b) == 123456?
You can multiply a by 10-to-the-power-of-N, where N is the number of digits in b, then add that number to b.
Less efficiently, you can convert both to strings, concatenate them, then parse that string into an integer.
In either case, there is a possibility of integer overflow.
If b is allowed to be negative, you will have to further define the desired result.
First find the number of digits in "b"
This can be done as follows:
int find_num_digits(int b)
{
int i = 0;
while (b > 0)
{
b = b/10;
i++;
}
return i;
}
Then do:
c = a*10^find_num_digits(b) + b;
"c" is the result.
You will have to make sure that "c" doesn't go out-of-bounds.
int combine(int a, int b) {
return 1000*a + b;
}
More generically:
int combine(int a, int b) {
if (b==0) return a;
return combine(a, b/10)*10+ b%10;
}

stuck in GCD of 2 numbers in C using recursion

I am getting segmentation fault with the following program. I am trying to find out the GCD using recursive function. The code is:
#include<stdio.h>
int gcd(int a, int b)
{
int temp, g, c;
if(a>b)
{
c=a;
a=b;
b=c;
}
//printf("The values of a and b are: %d %d",a,b);
temp = a % b;
if(temp != 0)
{
g = gcd(b, temp);
return(g);
}
if(temp == 0)
g= b;
return g;
}
int main()
{
int a,b;
printf("Enter two numbers: \n");
scanf("%d %d", &a, &b);
printf("The GCD of two numbers you entered are: %d\n", gcd(a,b));
}
The problem that I found out is in swapping variables. If I am removing it then the code is working fine. Can anybody tell me where I am going wrong? I am trying to implement it using Euclidean algorithm. So no other method can be implemented.
if(a>b)
{
c=a;
a=b;
b=c;
}
temp = a % b;
The problem is here. First, you're making sure that b > a. Now, if b is greater than a, it's not difficult to prove that a % b == a. For instance, 2 % 5 = 2.
Just replace the last line with
temp = b % a;
or, even better, reverse the condition for swapping :
if(a < b)
Instead of swapping the variables at the GCD function,Find the max number and send it as a and min number as b in the main function itself.
int GCD(int a, int b)
{
if (b == 0)
return a;
else
return GCD(b, a % b);
}
The condition should be
if (a < b)
Because doing
// Pre-condition: a >= b
temp = a % b;
// Post-condition: temp < b or temp == 0.
then the call gcd(b, temp)
has: temp < b, b <= min(original a, original b)
And so gcd terminates (variant a + b getting smaller on every call).
i think there is no need for the if (a > b) test, just remove it. If a >= b, the code works just as you want; if not, the first recursive call just do the swap.
You really don't need to check for each step which is greater (a or b).
Use following function to calculate gcd of two numbers.
int gcd(int a ,int b){
if(a % b == 0)
return b;
return gcd(b,a%b);
}
That's it.
Why to complicate things that much? Use this:
int findgcd(int x,int y){
while(x!=y){
if(x>y)
return findgcd(x-y,y);
else
return findgcd(x,y-x);
}
return x;
}

Given two int numbers A and B. How to find next multiple of B that is not less than A?

Suppose you input A = 15, B = 6, The answer is 18. What algorithm do I need?
This is what I try, but it doesn't work:
#include <stdio.h>
int main() {
int a, b;
scanf("%d %d", &a, &b);
for ( ; a % b != 0; a++ ) {
if ( a % b == 0 ) {
printf("%d\n", a);
return a;
}
}
return 0;
}
I get infinite loop.
The question (now) asks for:
The next multiple of b that is not less than a?
Using your notation of a and b, you can write it directly like this:
int NextMultipleUp(int a, int b)
{
int r = a % b;
if (r == 0)
return a;
else
return a + b - r;
}
The question originally asked for
The next multiple of a that is not greater than b
And for that the answer is
int NextMultipleDown(int a, int b)
{
return b - b % a;
}
This was the answer for which the original comments applied to.
return (((a-1) / b )+1) * b;
Always returns a multiple of b. Increment the integer dividend to get a multiple that is larger than the original a - subtract one from the original, because we want 'not less than' rather than 'greater than' a
I think that you want a do - while iterative loop, so I will give an alternative answer.
How to find next multiple of B that is not less than A?
Obviously this code is slower than David's.
int main ( void ){
int a, b, c;
long int result;
scanf("%d %d", &a, &b);
c = 0;
do {
result = b * c;
c++;
} while ( result < a );
printf( " The number is: %d \n", result );
}
int nextMultiple(int a,int b)
{
if(a%b == 0) return a;
return a+(b-(a%b));
}
so if a=15 b=6
the ans is
=15+(6-(15%6))
=15+(6-(3))
=15+3
=18

Find maximum of three number in C without using conditional statement and ternary operator

I have to find maximum of three number provided by user but with some restrictions. Its not allowed to use any conditional statement. I tried using ternary operator like below.
max=(a>b?a:b)>c?(a>b?a:b):c
But again its restricted to use ternary operator.
Now I am not getting any idea how to do this?
Taking advantage of short-circuiting in boolean expressions:
int max(int a, int b, int c)
{
int m = a;
(m < b) && (m = b); //these are not conditional statements.
(m < c) && (m = c); //these are just boolean expressions.
return m;
}
Explanation:
In boolean AND operation such as x && y, y is evaluated if and only if x is true. If x is false, then y is not evaluated, because the whole expression would be false which can be deduced without even evaluating y. This is called short-circuiting when the value of a boolean expression can be deduced without evaluating all operands in it.
Apply this principle to the above code. Initially m is a. Now if (m < b) is true, then that means, b is greater than m (which is actually a), so the second subexpression (m = b) is evaluated and m is set to b. If however (m < b) is false, then second subexpression will not be evaluated and m will remain a (which is greater than b). In a similar way, second expression is evaluated (on the next line).
In short, you can read the expression (m < x) && (m = x) as follows : set m to x if and only if m is less than x i.e (m < x) is true. Hope this helps you understanding the code.
Test code:
int main() {
printf("%d\n", max(1,2,3));
printf("%d\n", max(2,3,1));
printf("%d\n", max(3,1,2));
return 0;
}
Output:
3
3
3
Note the implementation of max gives warnings because evaluated expressions are not used:
prog.c:6: warning: value computed is not used
prog.c:7: warning: value computed is not used
To avoid these (harmless) warnings, you can implement max as:
int max(int a, int b, int c)
{
int m = a;
(void)((m < b) && (m = b)); //these are not conditional statements.
(void)((m < c) && (m = c)); //these are just boolean expressions.
return m;
}
The trick is that now we're casting the boolean expressions to void, which causes suppression of the warnings:
Assuming you are dealing with integers, how about:
#define max(x,y) (x ^ ((x ^ y) & -(x < y)))
int max3(int x, int y, int z) {
return max(max(x,y),z);
}
Just to add another alternative to avoid conditional execution (which is not the one I would use, but seemed missing from the set of solutions):
int max( int a, int b, int c ) {
int l1[] = { a, b };
int l2[] = { l1[ a<b ], c };
return l2[ l2[0] < c ];
}
The approach uses (as most others), the fact that the result of a boolean expression when converted to int yields either 0 or 1. The simplified version for two values would be:
int max( int a, int b ) {
int lookup[] { a, b };
return lookup[ a < b ];
}
If the expression a<b is correct we return b, carefully stored in the first index of the lookup array. If the expression yields false, then we return a that is stored as element 0 of the lookup array. Using this as a building block, you can say:
int max( int a, int b, int c ) {
int lookup[ max(a,b), c ];
return lookup[ max(a,b) < c ];
}
Which can be trivially transformed to the code above by avoiding the second call to the inner max using the result already stored in lookup[0] and inlining the original call to max(int,int).
(This part is just another proof that you have to measure before jumping into conclusions, see the edit at the end)
As to which would I actually use... well, probably the one by #Foo Baa here modified to use an inline function rather than a macro. The next option would be either this one or the one by #MSN here.
The common denominator of these three solutions not present in the accepted answer is that they do not only avoid the syntactic construct of if or the ternary operator ?:, but that they avoid branching altogether, and that can have an impact in performance. The branch-predictor in the CPU cannot possibly miss when there are no branches.
When considering performance, first measure then think
I have actually implemented a few of the different options for a 2-way max, and analyzed the generated code by the compiler. The following three solutions generate all the same assembly code:
int max( int a, int b ) { if ( a < b ) return b; else return a; }
int max( int a, int b ) { return (a < b? b : a ); }
int max( int a, int b ) {
(void)((a < b) && (a = b));
return a;
}
Which is not surprising, since all of the three represent the exact same operation. The interesting bit of information is that the generated code does not contain any branch. The implementation is simple with the cmovge instruction (test carried out with g++ in an intel x64 platform):
movl %edi, %eax # move a into the return value
cmpl %edi, %esi # compare a and b
cmovge %esi, %eax # if (b>a), move b into the return value
ret
The trick is in the conditional move instruction, that avoids any potential branch.
None of the other solutions has any branches, but all of them translate to more cpu instructions than any of this, which at the end of the day reassures us that we should always write simple code and let the compiler optimize it for us.
UPDATE: Looking at this 4 years later, I see that it fails badly if two or more of the values happen to be equal. Replacing > by >= changes the behavior, but doesn't fix the problem. It might still be salvageable, so I won't delete it yet, but don't use this in production code.
Ok, here's mine:
int max3(int a, int b, int c)
{
return a * (a > b & a > c) +
b * (b > a & b > c) +
c * (c > a & c > b);
}
Note that the use of & rather than && avoids any conditional code; it relies on the fact that > always yields 0 or 1. (The code generated for a > b might involve conditional jumps, but they're not visible from C.)
int fast_int_max(int a, int b)
{
int select= -(a < b);
unsigned int b_mask= select, a_mask= ~b_mask;
return (a&a_mask)|(b&b_mask);
}
int fast_int_max3(int a, int b, int c)
{
return fast_int_max(a, fast_int_max(b, c));
}
Boolean valued operators (including <, &&, etc) typically translate to conditional operations at the machine code level, so don't fulfill the spirit of the challenge. Here's a solution that any reasonable compiler would translate to only arithmetic instructions with no conditional jumps (assuming long has more bits than int and that long is 64 bits). The idea is that "m" captures and replicates the sign bit of b - a, so m is either all 1 bits (if a > b) or all zero bits (if a <= b). Note that long is used to avoid overflow. If for some reason you know that b - a doesn't over/under-flow, then the use of long isn't needed.
int max(int a, int b)
{
long d = (long)b - (long)a;
int m = (int)(d >> 63);
return a & m | b & ~m;
}
int max(int a, int b, int c)
{
long d;
int m;
d = (long)b - (long)a;
m = (int)(d >> 63);
a = a & m | b & ~m;
d = (long)c - (long)a;
m = (int)(d >> 63);
return a & m | c & ~m;
}
No conditionals. Only a cast to uint. Perfect solution.
int abs (a) { return (int)((unsigned int)a); }
int max (a, b) { return (a + b + abs(a - b)) / 2; }
int min (a, b) { return (a + b - abs(a - b)) / 2; }
void sort (int & a, int & b, int & c)
{
int max = max(max(a,b), c);
int min = min(min(a,b), c);
int middle = middle = a + b + c - max - min;
a = max;
b = middle;
c = min;
}
You can use this code to find largest out of two:
max{a,b} = abs(a-b)/2 + (a+b)/2
then use it again to find the third number:
max{a,b,c} = max(a,max(b,c))
See that this works for positive numbers you can change it to work for negative as well.
#include "stdafx.h"
#include <iostream>
int main()
{
int x,y,z;
scanf("%d %d %d", &x,&y, &z);
int max = ((x+y) + abs(x-y)) /2;
max = ((max+z) + abs(max-z)) /2;
printf("%d ", max);
return 0;
}
No conditional statements, just loops and assignments. And completely different form others' answers :)
while (a > b)
{
while (a > c)
{
tmp = a;
goto finish;
}
tmp = c;
goto finish;
}
while (b > c)
{
tmp = b;
goto finish;
}
tmp = c;
finish: max = tmp;
int compare(int a,int b, intc)
{
return (a > b ? (a > c ? a : c) : (b > c ? b : c))
}
Try this.
#include "stdio.h"
main() {
int a,b,c,rmvivek,arni,csc;
printf("enter the three numbers");
scanf("%d%d%d",&a,&b,&c);
printf("the biggest value is %d",(a>b&&a>c?a:b>c?b:c));
}
max = a > b ? ( a > c ? a : c ) : ( b > c ? b : c ) ;

Resources