Hello, I am making a program that takes a number, subtracts it until I get the kaprekar constant, everything is very good, I have done it from scratch and it works very well, but I do not understand why sometimes when I put certain numbers, it hangs like the number, for example 8456
. Here I show how it hangs:
The issue is that I'm using global variables because I can't return three values from a function that would be mayor1
, menor1
and fin
which would be the new value of the subtraction and that's why I think the problem arises. For example if I put another lower number eg. 1234
solves it for me:
Here is the code made from scratch by me so it won't be very efficient but I'm learning, here it is:
#include <iostream>
#include <sstream>
using namespace std;
int num1,z,l,peque,grande;
int numero,division,resto,i,a,j;
int arr[4];
int mayor[4];
int menor[4];
int mayor1;
int fin = 0;
int menor1;
int contador = 0;
int prueba(int num){
division = num;
resto = num;
for(i=0;i<=3;i++){
resto = division%10;
if(i==3){
arr[i] = division;
}else{
arr[i] = resto;
}
division/=10;
}
int o,mini,maxi,u;
mini=arr[0];
maxi=mini;
for(o=1;o<4;o++)
{
if (arr[o]<mini) mini=arr[o];
if (arr[o]>maxi) maxi=arr[o];
}
peque = 0;
for(z=0;z<4;z++){
num1=arr[z];
if(arr[z] != mini || arr[z] != maxi){
for(l=0;l<4;l++){
if(arr[l]<num1 && arr[l] != maxi && arr[l] != mini){
peque=arr[l];
}else if(arr[l]>peque && arr[l] != maxi && arr[l] != mini){
grande = arr[l];
}
}
}
}
mayor [0] = maxi;
mayor [1] = grande;
mayor [2] = peque;
mayor [3] = mini;
menor [0] = mini;
menor [1] = peque;
menor [2] = grande;
menor [3] = maxi;
stringstream ss;
ss<<menor[0]; //this can be run as a loop
ss<<menor[1];
ss<<menor[2];
ss<<menor[3];
ss>>menor1;
stringstream s;
s<<mayor[0]; //this can be run as a loop
s<<mayor[1];
s<<mayor[2];
s<<mayor[3];
s>>mayor1;
fin = mayor1 - menor1;
return fin;
}
int main(){
/* Declaramos el array y le damos valores */
cout << "Introduce un numero: ";
cin >> numero;
fin = numero;
while(fin!=6174){
fin=prueba(fin);
cout << fin << " = " << mayor1 << " - " << menor1;
cout << "\n";
contador++;
}
cout << "Numero de intentos: " << contador;
return 0;
}
The problem getting the middle numbers.
for(z=0;z<4;z++){
num1=arr[z];
if(arr[z] != mini || arr[z] != maxi){
for(l=0;l<4;l++){
if(arr[l]<num1 && arr[l] != maxi && arr[l] != mini){
peque=arr[l];
cout << peque;
}else if(arr[l]>num1 && arr[l] != maxi && arr[l] != mini){
grande = arr[l];
cout << grande;
}
}
}
The only way that occurred to me is to make a loop and then take and check it with everyone if it is not minimum or maximum and knowing if it is greater or less, then I take out the small or large, but so far I have not been able to optimize it correctly.
The kaprekar constant imposes a limitation and that is that the loop must not be repeated more than 7 times ... in this way endless loops like the one you mention are avoided.
Replace this:
For this: