Strange result obtained by testing combinations of sums or products in c
I have a problem with simple code. I want to have all products and sums of a certain number for EX 4 -> 0 + 4 1 + 3 2 + 2 3 + 1 4 + 0. for the sum, so I made this code for that:
#include <stdio.h>
#include <stdlib.h>
typedef struct{
unsigned int x;
unsigned int y;
}str;
const int MAX = 200000;
int main(int argc,char *argv[]){
int s=atoi(argv[1]);
if(s<0 || s>MAX){
printf("errore nummero incompatibile!\n");
exit(-1);
}
str sum;
int n=MAX;
for (sum.x=0;sum.x<n;sum.x++){
for (sum.y=0;sum.y<n;sum.y++){
if(strcmp(argv[2],"+")==0){
if(sum.x+sum.y==s){
printf("%d + %d = %d\n",sum.x,sum.y,s);
}
}else{
if(sum.x*sum.y==s){
printf("%d * %d = %d\n",sum.x,sum.y,s);
}
}
}
}
exit(-1);
}
argv [1] is the number for the test and argv [2] is the mode (sum or product)
here is the product output 44 *:
1 * 44 = 44
2 * 22 = 44
4 * 11 = 44
11 * 4 = 44
22 * 2 = 44
44 * 1 = 44
25266 * 169990 = 44
33998 * 126330 = 44
42110 * 101994 = 44
50532 * 84995 = 44
50997 * 84220 = 44
63165 * 67996 = 44
67996 * 63165 = 44
84220 * 50997 = 44
84995 * 50532 = 44
101994 * 42110 = 44
126330 * 33998 = 44
167378 * 179622 = 44
169990 * 25266 = 44
179622 * 167378 = 44`
it gives the correct result, but then it starts giving more numbers. they are the same every time i run it. what is it and how can i stop it?
source to share
You are iterating over every number up to MAX
causing an overflow along the way ( See vitaut's answer for an explanation of your problem and how to prevent overflow in your case, he explained it very well. ) It is not necessary. When you are trying to find every combination of multiplication by 2 integers, you just have to repeat to the specified number or MAX if the number is too large. Try to change
int n=MAX;
:
int n = s;
if (s > MAX)
int n=MAX;
source to share
This is caused by integer overflow :
25266 * 169990 == 4294967340
4294967340 is too large to be represented as unsigned int
, which is 32-bit on your platform. Thus, the most significant bits that do not fit are discarded, which gives you a modulo 2 to 32 result:
4294967340 mod 2**32 == 44
You can detect overflow in sum.x + sum.y
by checking to see if there is sum.x > UINT_MAX - sum.y
and either exit the inner loop or do something else. A similar check can be done for multiplication.
source to share