multiplication in C without arithmetic operators - c

Is it possible to multiply two numbers with out using arithmetic operators using C? Using the left shift operator, I can multiply any number by 2 only. How about other numbers?

To solve this problem, the first thing you want to do is figure out how to get simple arithmetic operations using just bitwise operators.
For example, addition can be achieved using this technique
int add(int a, int b) {
int c;
while (a != 0) {
c = b & a;
b = b ^ a;
c = c << 1;
a = c;
}
return b;
}
Then it's a matter of doing multiplication using addition:
int mult(int a, int b) {
int i = 0;
int c = 0;
while (i < b) {
c = add(c, a);
i = add(i, 1);
}
return c;
}
This multiplication doesn't yet work if b is negative, but since this looks like a homework problem, I'll leave that as an exercise for you. ;)
Edit:
While multiplication is intuitive once you have addition, the addition function is not so easy to understand, so I'll explain it here.
Let's say you want to add two numbers, 11010011 and 10101. The usual way to do it is to line them up like so:
11010011
+ 10101
You'll notice that when you add two binary numbers, if the ith bit from both numbers is 1, then the resulting bit is 0, and there is a carry over to a bit to the left of i.
This carry is what the variable 'c' in the code stores.
//...
c = b & a;
//...
c << 1;
//...
We bit wise and b and a to get only the bits where both a and b are 1, then we left shift it by 1 to get the carry bits.
Then you can look at the bits where a and b differ, i.e. one of the bits is 1 and the other bit is 0. The resulting bit in this case will be 1 with no carry.
that's what this line stores:
b = b ^ a;
The line above essentially removes the bits where both a and b are 1 (now stored in c).
So now you have another two numbers b and c, that you need to add together.
First let's look at where we're at with the example after the first iteration of the loop
c = a = 00100010
b = 11000110
It might not be entirely obvious yet, but b is accumulating the resulting sum. Through more iterations of the loop, more bits that are carried over are "added" back to b, with carries stored again in c. In that sense, you can think of the xor operator as an addition operation without carry.
Here's the second iteration of that loop:
c = a = 00000010
b = 11100100
3rd iteration:
c = a = 00000000
b = 11100110
Now c (and a) is 0, so there is no more carry to add. We exit the loop and return b. Note that even if you continue the loop, none of the numbers will change.

It is possible, see this wiki for a direction: http://en.wikipedia.org/wiki/Binary_multiplier

void main()
{
int n1, n2, n3, n4, x, y, i;
printf("Enter first number");
scanf("%d", &n1);
printf("Enter second number");
scanf("%d", &n2);
n3 = n2;
n4 = n2;
n1-=1;
for(i = n1;i > 0;i-=1)
{
do {
x = n2 & n3;
y= n2 ^ n3;
n2 = x << 1;
n3 = y;
} while (x);
n2 = y;
n3 = n4;
}
printf("product of two number is %d", y);
getch();
}

Yes it is possible. You can do it with logical operators. After all, that's all that the hardware does when you use an arithmetic operator.

Related

Find the flag from a RSA encryption written in C with no modulus

So I'm doing a practice Capture The Flag problem, The problem reads:
I was trying to implement RSA in C but I forgot the modulus. But I think this might be good enough already?
And then there is this code written in C attached to the question:
#include <stdio.h>
int main()
{
unsigned long long int flag1 = <redacted>;
flag1++;
unsigned long long int flag2 = <redacted>;
unsigned long long int ct1 = 1;
unsigned long long int ct2 = 1;
for (int i = 0; i<65537; i++)
{
ct1 = ct1 * flag1;
ct2 = ct2 * flag2;
}
printf("%llu\n",ct1);
printf("%llu\n",ct2);
}
/*OUTPUT:
7904812928421683021
16220282676865089917
*/
I want to get the flag, that is I want to find the values of flag1 and flag2 which outputted ct1(7904812928421683021) and ct2(16220282676865089917) after running in the program. Therefore I want to get the values of flag1 and flag 2 which is indicated by 'redacted' in the program.
I've done some research and found that 65537 is the public key exponent also in the question it states that they forgot the modulus. I've been sitting at this problem for hours now and still couldn't find anything particularly useful. I'm a beginner at cryptography so any help would be greatly appreciated.
If anyone of you could help it would mean a lot.
Thank you.
By appearances, unsigned long long int is 64 bits in the C implementation being used, so the arithmetic is performed modulo 264.
The loop that multiplies by flag1 or flag2 65537 times computes flag165537 modulo 264 and flag265537 modulo 264. We are given the results 7904812928421683021 and 16220282676865089917. To find flag1 and flag2 prior to the loop, we want to compute the inverse function.
By a generalization of Fermat’s little theorem, a𝜑(n) ≡ 1 mod n, where 𝜑 is Euler’s totient function. This means that exponentiating modulo n by 𝜑(n) is the same as exponentiating modulo n by 0, which means that exponentiation modulo n works modulo 𝜑(n) in the exponent. In other words, ab ≡ ac mod n if b ≡ c mod 𝜑(n).
The way this is useful to us is that when we have ab mod n, if we can find a c such that bc ≡ 1 mod 𝜑(n), then we can compute (ab)c mod n = abc mod n = a1 mod n = a mod n.
The Wikipedia page for Euler’s totient function tells us 𝜑(n) = n•product(1−1/p for prime p|n). (That product is the multiplication of 1−1/p for each prime p that divides n.) Since our n is 264, the only prime that divides it is 2, for which 1−1/2 = ½, so 𝜑(264) = 264•½ = 263.
Then we need to find the c such that bc ≡ 1 mod 𝜑(n) for b = 65537 and 𝜑(n) = 263. This can be done with the extended Euclidean algorithm. However, since we only need to do it once, and the numbers involved are large enough to be awkward to do in common C implementations, we can simply ask Wolfram Alpha for 65537^-1 mod 2^64, for which it tells us 9,223,090,566,172,966,913.
Next, we need to be able to raise a number to the power of 9,223,090,566,172,966,913. As this would take too long to do by simple iterative multiplication, we can instead use the algorithm below:
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
/* This routine computes x**e modulo 2^64 by multiplying a running product by
each x**p such that p is a power of two whose corresponding bit is set in
e. Thus, if e is 19, which is 10011 in binary, the powers of two
represented in it are 2^16, 2^1, and 2^0, so we multiply the running
product by x^(2^0), x^(2^1), and x^(2^16), yielding x^(2^0 + 2^1 + 2^16) =
x^19.
*/
static uint64_t pow_u64(uint64_t x, uint64_t e)
{
uint64_t y = 1; // Initialize running product to 1.
while (e) // Continue while bits remain in exponent.
{
if (e & 1) // If current bit is set, multiply by power of x.
y *= x;
x *= x; // Update to next x to a power-of-two.
e >>= 1; // Update e to move next bit into low position.
}
return y;
}
static void Do(uint64_t y)
{
uint64_t c = 9223090566172966913u;
printf("%" PRIu64 " ^ %" PRIu64 " = %" PRIu64 ".\n", y, c, pow_u64(y, c));
}
int main(void)
{
Do(7904812928421683021u);
Do(16220282676865089917u);
}
This produces the output:
7904812928421683021 ^ 9223090566172966913 = 7380380986431332173.
16220282676865089917 ^ 9223090566172966913 = 5716833052698820989.
from which we see the values of flag1 and flag2 before the loop are 7,380,380,986,431,332,173 and 5,716,833,052,698,820,989.
Since flag1 was incremented with ++ after it was initialized by <redacted>, we subtract 1 to get the initial value, 7,380,380,986,431,332,172. flag2 was directly initialized with 5,716,833,052,698,820,989.

Swapping numbers using multiplication method is not working in C

Recently I have been coding in C and I was trying to solve a number swapping problem. I have done it the easier way, by using a temporary variable. But my instructor told me use another method without temp variable. This is my code:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int a,b,temp;
printf("Enter two numbers: ");
scanf("%d%d",&a,&b);
printf("Entered Numbers:%d,%d \n",a,b);
temp = a; //This method is the easiest one.
a = b;
b = temp;
printf("Numbers are swapped as: %d,%d \n",a,temp);
a = (a*b)/a;
b = (a*b)/b;
printf("Numbers are swapped as: %d,%d",a,b);
return EXIT_SUCCESS;
}
I got the output as follows:
Enter two numbers: 50 32
Entered Numbers:50,32
Numbers swapped with temp are: 32,50
Numbers swapped without temp are: 50,50
Can anyone guess what might be the error? I believe my math is right, but why is it showing like this?
You have made a silly mistake in your second logic, just replace with mentioned one:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int a,b,temp;
printf("Enter two numbers: ");
scanf("%d%d",&a,&b);
printf("Entered Numbers:%d,%d \n",a,b);
temp = a; //This method is the easiest one.
a = b;
b = temp;
printf("Numbers are swapped as: %d,%d \n",a,temp);
a = a * b; //Change 1
b = a / b; //Change 2
a = a / b; //Change 3
printf("Numbers are swapped as: %d,%d",a,b);
return EXIT_SUCCESS;
}
You made a mistake in the swapping code: the multiplication method uses 3 steps:
compute the product a * b into a
divide a by b into b, effectively setting b to the original value of a.
divide a by b into a, effectively dividing the product by the original value of a, hence setting a to the original value of b.
The problem with this approach is it does not work for many cases:
if b is zero, the first division has undefined behavior, crashing the program in many cases
if a is zero, the second division has undefined behavior.
if a * b exceeds the range of type int, you also have undefined behavior, producing incorrect results or even a crash (try swapping 65536 and 65536).
There is another method without a temporary variable the is much safer and reliable: instead of multiplying the numbers and dividing the product, you can xor the numbers and use xor again to retrieve the original values and swap them.
Note also that your third printf statement is incorrect: you print the value of temp instead of b.
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
int main() {
int a, b, temp;
printf("Enter two numbers: ");
if (scanf("%d%d", &a, &b) != 2)
return EXIT_FAILURE;
printf("Entered Numbers: %d,%d\n", a, b);
temp = a; //This method is the easiest one.
a = b;
b = temp;
printf("Numbers are swapped with temp as: %d,%d\n", a, b);
a = a ^ b;
b = a ^ b;
a = a ^ b;
printf("Numbers are swapped with xor as: %d,%d\n", a, b);
a = a * b;
b = a / b;
a = a / b;
printf("Numbers are swapped with multiplication as: %d,%d\n", a, b);
return EXIT_SUCCESS;
}
Sample runs without optimisations:
Enter two numbers: 12 42
Entered Numbers: 12,42
Numbers are swapped with temp as: 42,12
Numbers are swapped with xor as: 12,42
Numbers are swapped with multiplication as: 42,12
Enter two numbers: 1 0
Entered Numbers: 1,0
Numbers are swapped with temp as: 0,1
Numbers are swapped with xor as: 1,0
Floating point exception: 8
Enter two numbers: 65536 65536
Entered Numbers: 65536,65536
Numbers are swapped with temp as: 65536,65536
Numbers are swapped with xor as: 65536,65536
Floating point exception: 8
The same runs with optimisations (clang or gcc):
Enter two numbers: 12 42
Entered Numbers: 12,42
Numbers are swapped with temp as: 42,12
Numbers are swapped with xor as: 12,42
Numbers are swapped with multiplication as: 42,12
Enter two numbers: 1 0
Entered Numbers: 1,0
Numbers are swapped with temp as: 0,1
Numbers are swapped with xor as: 1,0
Numbers are swapped with multiplication as: 0,1
Enter two numbers: 65536 65536
Entered Numbers: 65536,65536
Numbers are swapped with temp as: 65536,65536
Numbers are swapped with xor as: 65536,65536
Numbers are swapped with multiplication as: 65536,65536
What is going on? Is the compiler broken? As can be verified with Goldbolt's Compiler Explorer, when optimisations are turned on, both clang and gcc are able to identify the 3 swapping methods and generate the same swapping code with 4 mov instructions. Since the third method has undefined behavior on cases where the multiplication or division would fail, producing any result is OK, including the expected one. A blatant case of undefined behavior abuse. Your instructor should be amazed at this discovery.

Performing arithmetic operations in binary using only bitwise operators [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I multiply and divide using only bit shifting and adding?
I have to write functions to perform binary subtraction, multiplication, and division without using any arithmetic operators except for loop control. I've only written code in Java before now, so I'm having a hard time wrapping my head around this.
Starting with subtraction, I need to write a function with prototype
int bsub(int x, int y)
I know I need to convert y to two's complement in order to make it negative and add it to x, but I only know how to do this by using one's complement ~ operator and adding 1, but I can't use the + operator.
The badd function was provided, and I will be able to implement it in bsub if I can figure out how to make y a negative number. The code for badd is shown below. Thanks in advance for any tips.
int badd(int x,int y){
int i;
char sum;
char car_in=0;
char car_out;
char a,b;
unsigned int mask=0x00000001;
int result=0;
for(i=0;i<32;i++){
a=(x&mask)!=0;
b=(y&mask)!=0;
car_out=car_in & (a|b) |a&b;
sum=a^b^car_in;
if(sum) {
result|=mask;
}
if(i!=31) {
car_in=car_out;
} else {
if(car_in!=car_out) {
printf("Overflow occurred\n");
}
}
mask<<=1;
}
return result;
}
Well, subtracting in bitwise operations without the + or - operators is slightly tricky, but can be done. You have the basic idea with the complement, but without using + it becomes slightly tricky.
You can do it by first setting up addition with bit-wise only, then using that, you can do subtraction. Which is used for the complement, So the code looks like this:
int badd(int n1, int n2){
int carry, sum;
carry = (n1 & n2) << 1; // Find bits that are used for carry
sum = n1 ^ n2; // Add each bit, discard carry.
if (sum & carry) // If bits match, add current sum and carry.
return badd(sum, carry);
else
return sum ^ carry; // Return the sum.
}
int bsub(int n1, int n2){
// Add two's complement and return.
return badd(n1, badd(~n2, 1));
}
And then if we use the above code in an example:
int main(){
printf("%d\n", bsub(53, 17));
return 0;
}
Which ends up returning 36. And that is how subtraction works with bitwise only operations.
Afterwards multiplication and division get more complicated, but can be done; for those two operations, use shifts along with addition and/or subtraction to get the job done. You may also want to read this question and this article on how to do it.
You have to implement the binary addition first:
Example with 4 bits:
a = 1101
b = 1011
mask will range from 0001 to 1000
for (i=0;i<4;i++) {
x = a & pow(2, i); //mask, you can shift left as well
y = b & pow(2, i);
z = x ^ y; //XOR to calculate addition
z = z ^ carry; //add previous carry
carry = x & y | x ^ carry | y ^ carry; //new carry
}
This is pseudocode. The mask allows for operating bit by bit from left to right. You'll have to store z conveniently into another variable.
Once you have the addition, you'll be able to implement subtraction by 1'complementing and adding 1.
Multiplication goes the same way, but slightly more difficult. Basically it's the same division method you learned at school, using masks to select bits conveniently and adding the intermediate results using the addition above.
Division is a bit more complicated, it would take some more time to explain but basically it's the same principle.

Explain this snippet which finds the maximum of two integers without using if-else or any other comparison operator?

Find the maximum of two numbers. You should not use if-else or any other comparison operator. I found this question on online bulletin board, so i thought i should ask in StackOverflow
EXAMPLE
Input: 5, 10
Output: 10
I found this solution, can someone help me understand these lines of code
int getMax(int a, int b) {
int c = a - b;
int k = (c >> 31) & 0x1;
int max = a - k * c;
return max;
}
int getMax(int a, int b) {
int c = a - b;
int k = (c >> 31) & 0x1;
int max = a - k * c;
return max;
}
Let's dissect this. This first line appears to be straightforward - it stores the difference of a and b. This value is negative if a < b and is nonnegative otherwise. But there's actually a bug here - if the difference of the numbers a and b is so big that it can't fit into an integer, this will lead to undefined behavior - oops! So let's assume that doesn't happen here.
In the next line, which is
int k = (c >> 31) & 0x1;
the idea is to check if the value of c is negative. In virtually all modern computers, numbers are stored in a format called two's complement in which the highest bit of the number is 0 if the number is positive and 1 if the number is negative. Moreover, most ints are 32 bits. (c >> 31) shifts the number down 31 bits, leaving the highest bit of the number in the spot for the lowest bit. The next step of taking this number and ANDing it with 1 (whose binary representation is 0 everywhere except the last bit) erases all the higher bits and just gives you the lowest bit. Since the lowest bit of c >> 31 is the highest bit of c, this reads the highest bit of c as either 0 or 1. Since the highest bit is 1 iff c is 1, this is a way of checking whether c is negative (1) or positive (0). Combining this reasoning with the above, k is 1 if a < b and is 0 otherwise.
The final step is to do this:
int max = a - k * c;
If a < b, then k == 1 and k * c = c = a - b, and so
a - k * c = a - (a - b) = a - a + b = b
Which is the correct max, since a < b. Otherwise, if a >= b, then k == 0 and
a - k * c = a - 0 = a
Which is also the correct max.
Here we go: (a + b) / 2 + |a - b| / 2
Use bitwise hacks
r = x ^ ((x ^ y) & -(x < y)); // max(x, y)
If you know that INT_MIN <= x - y <= INT_MAX, then you can use the following, which is faster because (x - y) only needs to be evaluated once.
r = x - ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1))); // max(x, y)
Source : Bit Twiddling Hacks by Sean Eron Anderson
(sqrt( a*a + b*b - 2*a*b ) + a + b) / 2
This is based on the same technique as mike.dld's solution, but it is less "obvious" here what I am doing. An "abs" operation looks like you are comparing the sign of something but I here am taking advantage of the fact that sqrt() will always return you the positive square root so I am squaring (a-b) writing it out in full then square-rooting it again, adding a+b and dividing by 2.
You will see it always works: eg the user's example of 10 and 5 you get sqrt(100 + 25 - 100) = 5 then add 10 and 5 gives you 20 and divide by 2 gives you 10.
If we use 9 and 11 as our numbers we would get (sqrt(121 + 81 - 198) + 11 + 9)/2 = (sqrt(4) + 20) / 2 = 22/2 = 11
The simplest answer is below.
#include <math.h>
int Max(int x, int y)
{
return (float)(x + y) / 2.0 + abs((float)(x - y) / 2);
}
int Min(int x, int y)
{
return (float)(x + y) / 2.0 - abs((float)(x - y) / 2);
}
int max(int i, int j) {
int m = ((i-j) >> 31);
return (m & j) + ((~m) & i);
}
This solution avoids multiplication.
m will either be 0x00000000 or 0xffffffff
Using the shifting idea to extract the sign as posted by others, here's another way:
max (a, b) = new[] { a, b } [((a - b) >> 31) & 1]
This pushes the two numbers into an array with the maximum number given by the array-element whose index is sign bit of the difference between the two numbers.
Do note that:
The difference (a - b) may overflow.
If the numbers are unsigned and the >> operator refers to a logical right-shift, the & 1 is unnecessary.
Here's how I think I'd do the job. It's not as readable as you might like, but when you start with "how do I do X without using the obvious way of doing X, you have to kind of expect that.
In theory, this gives up some portability too, but you'd have to find a pretty unusual system to see a problem.
#define BITS (CHAR_BIT * sizeof(int) - 1)
int findmax(int a, int b) {
int rets[] = {a, b};
return rets[unsigned(a-b)>>BITS];
}
This does have some advantages over the one shown in the question. First of all, it calculates the correct size of shift, instead of being hard-coded for 32-bit ints. Second, with most compilers we can expect all the multiplication to happen at compile time, so all that's left at run time is trivial bit manipulation (subtract and shift) followed by a load and return. In short, this is almost certain to be pretty fast, even on the smallest microcontroller, where the original used multiplication that had to happen at run-time, so while it's probably pretty fast on a desktop machine, it'll often be quite a bit slower on a small microcontroller.
Here's what those lines are doing:
c is a-b. if c is negative, a<b.
k is 32nd bit of c which is the sign bit of c (assuming 32 bit integers. If done on a platform with 64 bit integers, this code will not work). It's shifted 31 bits to the right to remove the rightmost 31 bits leaving the sign bit in the right most place and then anding it with 1 to remove all the bits to the left (which will be filled with 1s if c is negative). So k will be 1 if c is negative and 0 if c is positive.
Then max = a - k * c. If c is 0, this means a>=b, so max is a - 0 * c = a. If c is 1, this means that a<b and then a - 1 * c = a - (a - b) = a - a + b = b.
In the overall, it's just using the sign bit of the difference to avoid using greater than or less than operations. It's honestly a little silly to say that this code doesn't use a comparison. c is the result of comparing a and b. The code just doesn't use a comparison operator. You could do a similar thing in many assembly codes by just subtracting the numbers and then jumping based on the values set in the status register.
I should also add that all of these solutions are assuming that the two numbers are integers. If they are floats, doubles, or something more complicated (BigInts, Rational numbers, etc.) then you really have to use a comparison operator. Bit-tricks will not generally do for those.
getMax() Function Without Any Logical Operation-
int getMax(int a, int b){
return (a+b+((a-b)>>sizeof(int)*8-1|1)*(a-b))/2;
}
Explanation:
Lets smash the 'max' into pieces,
max
= ( max + max ) / 2
= ( max + (min+differenceOfMaxMin) ) / 2
= ( max + min + differenceOfMaxMin ) / 2
= ( max + min + | max - min | ) ) / 2
So the function should look like this-
getMax(a, b)
= ( a + b + absolute(a - b) ) / 2
Now,
absolute(x)
= x [if 'x' is positive] or -x [if 'x' is negative]
= x * ( 1 [if 'x' is positive] or -1 [if 'x' is negative] )
In integer positive number the first bit (sign bit) is- 0; in negative it is- 1. By shifting bits to the right (>>) the first bit can be captured.
During right shift the empty space is filled by the sign bit. So 01110001 >> 2 = 00011100, while 10110001 >> 2 = 11101100.
As a result, for 8 bit number shifting 7 bit will either produce- 1 1 1 1 1 1 1 [0 or 1] for negative, or 0 0 0 0 0 0 0 [0 or 1] for positive.
Now, if OR operation is performed with 00000001 (= 1), negative number yields- 11111111 (= -1), and positive- 00000001 (= 1).
So,
absolute(x)
= x * ( 1 [if 'x' is positive] or -1 [if 'x' is negative] )
= x * ( ( x >> (numberOfBitsInInteger-1) ) | 1 )
= x * ( ( x >> ((numberOfBytesInInteger*bitsInOneByte) - 1) ) | 1 )
= x * ( ( x >> ((sizeOf(int)*8) - 1) ) | 1 )
Finally,
getMax(a, b)
= ( a + b + absolute(a - b) ) / 2
= ( a + b + ((a-b) * ( ( (a-b) >> ((sizeOf(int)*8) - 1) ) | 1 )) ) / 2
Another way-
int getMax(int a, int b){
int i[] = {a, b};
return i[( (i[0]-i[1]) >> (sizeof(int)*8 - 1) ) & 1 ];
}
static int mymax(int a, int b)
{
int[] arr;
arr = new int[3];
arr[0] = b;
arr[1] = a;
arr[2] = a;
return arr[Math.Sign(a - b) + 1];
}
If b > a then (a-b) will be negative, sign will return -1, by adding 1 we get index 0 which is b, if b=a then a-b will be 0, +1 will give 1 index so it does not matter if we are returning a or b, when a > b then a-b will be positive and sign will return 1, adding 1 we get index 2 where a is stored.
#include<stdio.h>
main()
{
int num1,num2,diff;
printf("Enter number 1 : ");
scanf("%d",&num1);
printf("Enter number 2 : ");
scanf("%d",&num2);
diff=num1-num2;
num1=abs(diff);
num2=num1+diff;
if(num1==num2)
printf("Both number are equal\n");
else if(num2==0)
printf("Num2 > Num1\n");
else
printf("Num1 > Num2\n");
}
The code which I am providing is for finding maximum between two numbers, the numbers can be of any data type(integer, floating). If the input numbers are equal then the function returns the number.
double findmax(double a, double b)
{
//find the difference of the two numbers
double diff=a-b;
double temp_diff=diff;
int int_diff=temp_diff;
/*
For the floating point numbers the difference contains decimal
values (for example 0.0009, 2.63 etc.) if the left side of '.' contains 0 then we need
to get a non-zero number on the left side of '.'
*/
while ( (!(int_diff|0)) && ((temp_diff-int_diff)||(0.0)) )
{
temp_diff = temp_diff * 10;
int_diff = temp_diff;
}
/*
shift the sign bit of variable 'int_diff' to the LSB position and find if it is
1(difference is -ve) or 0(difference is +ve) , then multiply it with the difference of
the two numbers (variable 'diff') then subtract it with the variable a.
*/
return a- (diff * ( int_diff >> (sizeof(int) * 8 - 1 ) & 1 ));
}
Description
The first thing the function takes the arguments as double and has return type as double. The reason for this is that to create a single function which can find maximum for all types. When integer type numbers are provided or one is an integer and other is the floating point then also due to implicit conversion the function can be used to find the max for integers also.
The basic logic is simple, let's say we have two numbers a & b if a-b>0(i.e. the difference is positive) then a is maximum else if a-b==0 then both are equal and if a-b<0(i.e. diff is -ve) b is maximum.
The sign bit is saved as the Most Significant Bit(MSB) in the memory. If MSB is 1 and vice-versa. To check if MSB is 1 or 0 we shift the MSB to the LSB position and Bitwise & with 1, if the result is 1 then the number is -ve else no. is +ve. This result is obtained by the statement:
int_diff >> (sizeof(int) * 8 - 1 ) & 1
Here to get the sign bit from the MSB to LSB we right shift it to k-1 bits(where k is the number of bits needed to save an integer number in the memory which depends on the type of system). Here k= sizeof(int) * 8 as sizeof() gives the number of bytes needed to save an integer to get no. of bits, we multiply it with 8. After the right shift, we apply the bitwise & with 1 to get the result.
Now after obtaining the result(let us assume it as r) as 1(for -ve diff) and 0(for +ve diff) we multiply the result with the difference of the two numbers, the logic is given as follows:
if a>b then a-b>0 i.e., is +ve so the result is 0(i.e., r=0). So a-(a-b)*r => a-(a-b)*0, which gives 'a' as the maximum.
if a < b then a-b<0 i.e., is -ve so the result is 1(i.e., r=1). So a-(a-b)*r => a-(a-b)*1 => a-a+b =>b , which gives 'b' as the maximum.
Now there are two remaining points 1. the use of while loop and 2. why I have used the variable 'int_diff' as an integer. To answer these properly we have to understand some points:
Floating type values cannot be used as an operand for the bitwise operators.
Due to above reason, we need to get the value in an integer value to get the sign of difference by using bitwise operators. These two points describe the need of variable 'int_diff' as integer type.
Now let's say we find the difference in variable 'diff' now there are 3 possibilities for the values of 'diff' irrespective of the sign of these values. (a). |diff|>=1 , (b). 0<|diff|<1 , (c). |diff|==0.
When we assign a double value to integer variable the decimal part is lost.
For case(a) the value of 'int_diff' >0 (i.e.,1,2,...). For other two cases int_diff=0.
The condition (temp_diff-int_diff)||0.0 checks if diff==0 so both numbers are equal.
If diff!=0 then we check if int_diff|0 is true i.e., case(b) is true
In the while loop, we try to get the value of int_diff as non-zero so that the value of int_diff also gets the sign of diff.
Here are a couple of bit-twiddling methods to get the max of two integral values:
Method 1
int max1(int a, int b) {
static const size_t SIGN_BIT_SHIFT = sizeof(a) * 8 - 1;
int mask = (a - b) >> SIGN_BIT_SHIFT;
return (a & ~mask) | (b & mask);
}
Explanation:
(a - b) >> SIGN_BIT_SHIFT - If a > b then a - b is positive, thus the sign bit is 0, and the mask is 0x00.00. Otherwise, a < b so a - b is negative, the sign bit is 1 and after shifting, we get a mask of 0xFF..FF
(a & ~mask) - If the mask is 0xFF..FF, then ~mask is 0x00..00 and then this value is 0. Otherwise, ~mask is 0xFF..FF and the value is a
(b & mask) - If the mask is 0xFF..FF, then this value is b. Otherwise, mask is 0x00..00 and the value is 0.
Finally:
If a >= b then a - b is positive, we get max = a | 0 = a
If a < b then a - b is negative, we get max = 0 | b = b
Method 2
int max2(int a, int b) {
static const size_t SIGN_BIT_SHIFT = sizeof(a) * 8 - 1;
int mask = (a - b) >> SIGN_BIT_SHIFT;
return a ^ ((a ^ b) & mask);
}
Explanation:
Mask explanation is the same as for Method 1. If a > b the mask is 0x00..00, otherwise the mask is 0xFF..FF
If the mask is 0x00..00, then (a ^ b) & mask is 0x00..00
If the mask is 0xFF..FF, then (a ^ b) & mask is a ^ b
Finally:
If a >= b, we get a ^ 0x00..00 = a
If a < b, we get a ^ a ^ b = b
//In C# you can use math library to perform min or max function
using System;
class NumberComparator
{
static void Main()
{
Console.Write(" write the first number to compare: ");
double first_Number = double.Parse(Console.ReadLine());
Console.Write(" write the second number to compare: ");
double second_Number = double.Parse(Console.ReadLine());
double compare_Numbers = Math.Max(first_Number, second_Number);
Console.Write("{0} is greater",compare_Numbers);
}
}
No logical operators, no libs (JS)
function (x, y) {
let z = (x - y) ** 2;
z = z ** .5;
return (x + y + z) / 2
}
The logic described in a problem can be explained as if 1st number is smaller then 0 will be subtracted else difference will be subtracted from 1st number to get 2nd number.
I found one more mathematical solution which I think is bit simpler to understand this concept.
Considering a and b as given numbers
c=|a/b|+1;
d=(c-1)/b;
smallest number= a - d*(a-b);
Again,The idea is to find k which is wither 0 or 1 and multiply it with difference of two numbers.And finally this number should be subtracted from 1st number to yield the smaller of the two numbers.
P.S. this solution will fail in case 2nd number is zero
There is one way
public static int Min(int a, int b)
{
int dif = (int)(((uint)(a - b)) >> 31);
return a * dif + b * (1 - dif);
}
and one
return (a>=b)?b:a;
int a=151;
int b=121;
int k=Math.abs(a-b);
int j= a+b;
double k1=(double)(k);
double j1= (double) (j);
double c=Math.ceil(k1/2) + Math.floor(j1/2);
int c1= (int) (c);
System.out.println(" Max value = " + c1);
Guess we can just multiply the numbers with their bitwise comparisons eg:
int max=(a>b)*a+(a<=b)*b;

Find Pythagorean triplet for which a + b + c = 1000

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
Source: http://projecteuler.net/index.php?section=problems&id=9
I tried but didn't know where my code went wrong. Here's my code in C:
#include <math.h>
#include <stdio.h>
#include <conio.h>
void main()
{
int a=0, b=0, c=0;
int i;
for (a = 0; a<=1000; a++)
{
for (b = 0; b<=1000; b++)
{
for (c = 0; c<=1000; c++)
{
if ((a^(2) + b^(2) == c^(2)) && ((a+b+c) ==1000)))
printf("a=%d, b=%d, c=%d",a,b,c);
}
}
}
getch();
}
#include <math.h>
#include <stdio.h>
int main()
{
const int sum = 1000;
int a;
for (a = 1; a <= sum/3; a++)
{
int b;
for (b = a + 1; b <= sum/2; b++)
{
int c = sum - a - b;
if ( a*a + b*b == c*c )
printf("a=%d, b=%d, c=%d\n",a,b,c);
}
}
return 0;
}
explanation:
b = a;
if a, b (a <= b) and c are the Pythagorean triplet,
then b, a (b >= a) and c - also the solution, so we can search only one case
c = 1000 - a - b;
It's one of the conditions of the problem (we don't need to scan all possible 'c': just calculate it)
I'm afraid ^ doesn't do what you think it does in C. Your best bet is to use a*a for integer squares.
Here's a solution using Euclid's formula (link).
Let's do some math:
In general, every solution will have the form
a=k(x²-y²)
b=2kxy
c=k(x²+y²)
where k, x and y are positive integers, y < x and gcd(x,y)=1 (We will ignore this condition, which will lead to additional solutions. Those can be discarded afterwards)
Now, a+b+c= kx²-ky²+2kxy+kx²+ky²=2kx²+2kxy = 2kx(x+y) = 1000
Divide by 2: kx(x+y) = 500
Now we set s=x+y: kxs = 500
Now we are looking for solutions of kxs=500, where k, x and s are integers and x < s < 2x.
Since all of them divide 500, they can only take the values 1, 2, 4, 5, 10, 20, 25, 50, 100, 125, 250, 500. Some pseudocode to do this for arbitrary n (it and can be done by hand easily for n=1000)
If n is odd
return "no solution"
else
L = List of divisors of n/2
for x in L
for s in L
if x< s <2*x and n/2 is divisible by x*s
y=s-x
k=((n/2)/x)/s
add (k*(x*x-y*y),2*k*x*y,k*(x*x+y*y)) to list of solutions
sort the triples in the list of solutions
delete solutions appearing twice
return list of solutions
You can still improve this:
x will never be bigger than the root of n/2
the loop for s can start at x and stop after 2x has been passed (if the list is ordered)
For n = 1000, the program has to check six values for x and depending on the details of implementation up to one value for y. This will terminate before you release the button.
As mentioned above, ^ is bitwise xor, not power.
You can also remove the third loop, and instead use
c = 1000-a-b; and optimize this a little.
Pseudocode
for a in 1..1000
for b in a+1..1000
c=1000-a-b
print a, b, c if a*a+b*b=c*c
There is a quite dirty but quick solution to this problem. Given the two equations
a*a + b*b = c*c
a+b+c = 1000.
You can deduce the following relation
a = (1000*1000-2000*b)/(2000-2b)
or after two simple math transformations, you get:
a = 1000*(500-b) / (1000 - b)
since a must be an natural number. Hence you can:
for b in range(1, 500):
if 1000*(500-b) % (1000-b) == 0:
print b, 1000*(500-b) / (1000-b)
Got result 200 and 375.
Good luck
#include <stdio.h>
int main() // main always returns int!
{
int a, b, c;
for (a = 0; a<=1000; a++)
{
for (b = a + 1; b<=1000; b++) // no point starting from 0, otherwise you'll just try the same solution more than once. The condition says a < b < c.
{
for (c = b + 1; c<=1000; c++) // same, this ensures a < b < c.
{
if (((a*a + b*b == c*c) && ((a+b+c) ==1000))) // ^ is the bitwise xor operator, use multiplication for squaring
printf("a=%d, b=%d, c=%d",a,b,c);
}
}
}
return 0;
}
Haven't tested this, but it should set you on the right track.
From man pow:
POW(3) Linux Programmer's Manual POW(3)
NAME
pow, powf, powl - power functions
SYNOPSIS
#include <math.h>
double pow(double x, double y);
float powf(float x, float y);
long double powl(long double x, long double y);
Link with -lm.
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
powf(), powl(): _BSD_SOURCE || _SVID_SOURCE || _XOPEN_SOURCE >= 600 || _ISOC99_SOURCE; or cc -std=c99
DESCRIPTION
The pow() function returns the value of x raised to the power of y.
RETURN VALUE
On success, these functions return the value of x to the power of y.
If x is a finite value less than 0, and y is a finite non-integer, a domain error occurs, and a NaN is
returned.
If the result overflows, a range error occurs, and the functions return HUGE_VAL, HUGE_VALF, or HUGE_VALL,
as you see, pow is using floating point arithmetic, which is unlikely to give you the exact result (although in this case should be OK, as relatively small integers have an exact representation; but don't rely on that for general cases)... use n*n to square the numbers in integer arithmetic (also, in modern CPU's with powerful floating point units the throughput can be even higher in floating point, but converting from integer to floating point has a very high cost in number of CPU cycles, so if you're dealing with integers, try to stick to integer arithmetic).
some pseudocode to help you optimise a little bit your algorithm:
for a from 1 to 998:
for b from 1 to 999-a:
c = 1000 - a - b
if a*a + b*b == c*c:
print a, b, c
In C the ^ operator computes bitwise xor, not the power. Use x*x instead.
I know this question is quite old, and everyone has been posting solutions with 3 for loops, which is not needed. I got this solved in O(n), by **equating the formulas**; **a+b+c=1000 and a^2 + b^2 = c^2**
So, solving further we get;
a+b = 1000-c
(a+b)^2 = (1000-c)^2
If we solve further we deduce it to;
a=((50000-(1000*b))/(1000-b)).
We loop for "b", and find "a".
Once we have "a" and "b", we get "c".
public long pythagorasTriplet(){
long a = 0, b=0 , c=0;
for(long divisor=1; divisor<1000; divisor++){
if( ((500000-(1000*divisor))%(1000-divisor)) ==0){
a = (500000 - (1000*divisor))/(1000-divisor);
b = divisor;
c = (long)Math.sqrt(a*a + b*b);
System.out.println("a is " + a + " b is: " + b + " c is : " + c);
break;
}
}
return a*b*c;
}
As others have mentioned you need to understand the ^ operator.
Also your algorithm will produce multiple equivalent answers with the parameters a,b and c in different orders.
While as many people have pointed out that your code will work fine once you switch to using pow. If your interested in learning a bit of math theory as it applies to CS, I would recommend trying to implementing a more effient version using "Euclid's formula" for generating Pythagorean triples (link).
Euclid method gives the perimeter to be m(m+n)= p/2 where m> n and the sides are m^2+n^2 is the hypotenuse and the legs are 2mn and m^2-n^2.thus m(m+n)=500 quickly gives m= 20 and n=5. The sides are 200, 375 and 425. Use Euclid to solve all pythorean primitive questions.
As there are two equations (a+b+c = 1000 && aˆ2 + bˆ2 = cˆ2) with three variables, we can solve it in linear time by just looping through all possible values of one variable, and then we can solve the other 2 variables in constant time.
From the first formula, we get b=1000-a-c, and if we replace b in 2nd formula with this, we get c^2 = aˆ2 + (1000-a-c)ˆ2, which simplifies to c=(aˆ2 + 500000 - 1000a)/(1000-a).
Then we loop through all possible values of a, solve c and b with the above formulas, and if the conditions are satisfied we have found our triplet.
int n = 1000;
for (int a = 1; a < n; a++) {
int c = (a*a + 500000 - 1000*a) / (1000 - a);
int b = (1000 - a - c);
if (b > a && c > b && (a * a + b * b) == c * c) {
return a * b * c;
}
}
for a in range(1,334):
for b in range(500, a, -1):
if a + b < 500:
break
c = 1000 - a - b
if a**2 + b**2 == c**2:
print(a,b,c)
Further optimization from Oleg's answer.
One side cannot be greater than the sum of the other two.
So a + b cannot be less than 500.
I think the best approach here is this:
int n = 1000;
unsigned long long b =0;
unsigned long long c =0;
for(int a =1;a<n/3;a++){
b=((a*a)- (a-n)*(a-n)) /(2*(a-n));
c=n-a-b;
if(a*a+b*b==c*c)
cout<<a<<' '<<b<<' '<<c<<endl;
}
explanation:
We shall refer to the N and A constant so we will not have to use two loops.
We can do it because
c=n-a-b and b=(a^2-(a-n)^2)/(2(a-n))
I got these formulas by solving a system of equations:
a+b+c=n,
a^2+b^2=c^2
func maxProd(sum:Int)->Int{
var prod = 0
// var b = 0
var c = 0
let bMin:Int = (sum/4)+1 //b can not be less than sum/4+1 as (a+b) must be greater than c as there will be no triangle if this condition is false and any pythagorus numbers can be represented by a triangle.
for b in bMin..<sum/2 {
for a in ((sum/2) - b + 1)..<sum/3{ //as (a+b)>c for a valid triangle
c = sum - a - b
let csquare = Int(pow(Double(a), 2) + pow(Double(b), 2))
if(c*c == csquare){
let newProd = a*b*c
if(newProd > prod){
prod = newProd
print(a,b,c)
}
}
}
}
//
return prod
}
The answers above are good enough but missing one important piece of information a + b > c. ;)
More details will be provided to those who ask.
with Python
def findPythagorean1000():
for c in range(1001):
for b in range(1,c):
for a in range(1,b):
if (a+b+c==1000):
if(pow(a,2)+pow(b,2)) ==pow(c,2):
print(a,b,c)
print(a*b*c)
return
findPythagorean1000()

Resources