To find hcf of n number by using only loops.
Managed C++/CLI
4
Posts
2
Posters
9
Views
1
Watching
-
This is the code i came up with but it's too long, how to short it down.
#include
#includeint main(){
int i=0, j, num[100], count=0, k, hcf[50], min;//entering integers, Enter 0 to exit the loop. printf("Enter your numbers: \\n"); do{ scanf("%d", &num\[i\]); i++; count++; }while(num\[i-1\]!=0); /\* here we find the minimum number, because we want to find the common factor, hence the factor cannot be > min number entered cause then it will not be common factor in all. Therefore the min number enterd can be the highest factor or the factors can be <= the min int entered. \*/ min = num\[0\]; for(j=1; j<=count-2; j++){ if(min>num\[j\]) min = num\[j\]; } //in the code below we find the factors of every integer entered. int h=0, n\[count-1\]; for(j=0; j<=count-2; j++){ for(k=1; k<=min; k++){ if(num\[j\]%k==0){ hcf\[h\]=k; h++; } } n\[j\] = h; /\*here h is the the size of the number of factors for every integer which is saved in n\[\] array\*/ } /\* In the loop below each factor of the 1st integer is compared with the factors of others number, And if the occurance of any factor of 1st is equal to the number of int intitially enterd then that is a common factor an it is saved in max\[\] array \*/ int c=0, max\[50\], z; for(i=0; i
-
This is the code i came up with but it's too long, how to short it down.
#include
#includeint main(){
int i=0, j, num[100], count=0, k, hcf[50], min;//entering integers, Enter 0 to exit the loop. printf("Enter your numbers: \\n"); do{ scanf("%d", &num\[i\]); i++; count++; }while(num\[i-1\]!=0); /\* here we find the minimum number, because we want to find the common factor, hence the factor cannot be > min number entered cause then it will not be common factor in all. Therefore the min number enterd can be the highest factor or the factors can be <= the min int entered. \*/ min = num\[0\]; for(j=1; j<=count-2; j++){ if(min>num\[j\]) min = num\[j\]; } //in the code below we find the factors of every integer entered. int h=0, n\[count-1\]; for(j=0; j<=count-2; j++){ for(k=1; k<=min; k++){ if(num\[j\]%k==0){ hcf\[h\]=k; h++; } } n\[j\] = h; /\*here h is the the size of the number of factors for every integer which is saved in n\[\] array\*/ } /\* In the loop below each factor of the 1st integer is compared with the factors of others number, And if the occurance of any factor of 1st is equal to the number of int intitially enterd then that is a common factor an it is saved in max\[\] array \*/ int c=0, max\[50\], z; for(i=0; i
-
can you tell where i can decrease the size of code or how it can be done in single loop ?
Yes, but this is your homework. Before you start coding try to write things out on paper and look at the best ways to get what you need. See how many things you can do in the first loop. For example, you can check each number to see if it is the smallest or largest as you read them in.