Advertisement
Programmin-in-Python

C Program that keeps count of the no. of steps of Kaprekar routine's execution

Jan 29th, 2022
806
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <stdbool.h>
  3.  
  4. void sort(int arr[], int n, bool reverse){
  5.     int i, j, key;
  6.  
  7.     if(reverse==true){
  8.         for(i=1;i<n;i++){
  9.             key=arr[i];
  10.             j=i-1;
  11.  
  12.             while(j>=0&&arr[j]<key){
  13.                 arr[j+1] = arr[j];
  14.                 j--;
  15.             }
  16.             arr[j+1]=key;
  17.         }
  18.     } else {
  19.         for(i=1;i<n;i++){
  20.             key=arr[i];
  21.             j=i-1;
  22.  
  23.             while(j>=0&&arr[j]>key){
  24.                 arr[j+1] = arr[j];
  25.                 j--;
  26.             }
  27.             arr[j+1]=key;
  28.         }
  29.     }
  30. }
  31.  
  32. int kaprekar_routine(int n, int diff){
  33.     if((1000>=n||n>=9999)&&(n!=0)){printf("Number should be only 4 digits"); return 0;}
  34.     int arr[4], arr_res[2], i=0, largest=0, smallest=0, ldiff;
  35.     static int res, steps=0;
  36.  
  37.     while(n>0){
  38.         arr[i] = n%10;
  39.         i++;
  40.         n /= 10;
  41.     }
  42.     sort(arr, 4, false);
  43.     for(i=0; i<4; i++){
  44.         smallest *= 10;
  45.         smallest += arr[i];
  46.     }
  47.     sort(arr, 4, true);
  48.     for(i=0; i<4; i++){
  49.         largest *= 10;
  50.         largest += arr[i];
  51.     }
  52.     ldiff = largest-smallest;
  53.     steps++;
  54.  
  55.     if((ldiff==diff)&&(ldiff!=0)){
  56.         return steps;
  57.     } else if(ldiff==0){
  58.         return 0;
  59.     } else {
  60.         return kaprekar_routine(ldiff, ldiff);
  61.     }
  62. }
  63.  
  64. int main(){
  65.     int overall_steps = kaprekar_routine(3456, 0);
  66.     printf("The Kaprekar Routine happened for %d steps", overall_steps);
  67.     return 0;
  68. }
Advertisement
Advertisement
Advertisement
RAW Paste Data Copied
Advertisement