codeparrot/xlcost-text-to-code huggingface dataset:
GCD of two numbers formed by n repeating x and y times | Return the Greatest common Divisor of two numbers . ; Prints Greatest Common Divisor of number formed by n repeating x times and y times . ; Finding GCD of x and y . ; Print n , g times . ; Driven Program
function gcd ( a , b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } function findgcd ( n , x , y ) { let g = gcd ( x , y ) ; for ( let i = 0 ; i < g ; i ++ ) document . write ( n ) ; } let n = 123 , x = 5 , y = 2 ; findgcd ( n , x , y ) ;
Count natural numbers whose factorials are divisible by x but not y | GCD function to compute the greatest divisor among a and b ; Returns first number whose factorial is divisible by x . ; let i = 1 ; Result ; Remove common factors ; We found first i . ; Count of natural numbers whose factorials are divisible by x but not y . ; Return difference between first natural number whose factorial is divisible by y and first natural number whose factorial is divisible by x . ; Driver code
function gcd ( a , b ) { if ( ( a % b ) == 0 ) return b ; return gcd ( b , a % b ) ; } function firstFactorialDivisibleNumber ( x ) { let new_x = x ; for ( i = 1 ; i < x ; i ++ ) { new_x /= gcd ( i , new_x ) ; if ( new_x == 1 ) break ; } return i ; } function countFactorialXNotY ( x , y ) { return ( firstFactorialDivisibleNumber ( y ) - firstFactorialDivisibleNumber ( x ) ) ; } let x = 15 , y = 25 ; document . write ( countFactorialXNotY ( x , y ) ) ;
Find the first natural number whose factorial is divisible by x | Returns first number whose factorial divides x . ; var i = 1 ; Result ; Driver code
function firstFactorialDivisibleNumber ( x ) { var fact = 1 ; for ( i = 1 ; i < x ; i ++ ) { fact = fact * i ; if ( fact % x == 0 ) break ; } return i ; } var x = 16 ; document . write ( firstFactorialDivisibleNumber ( x ) ) ;
Find two prime numbers with given sum | Generate all prime numbers less than n . ; Initialize all entries of boolean array as true . A value in isPrime [ i ] will finally be false if i is Not a prime , else true bool isPrime [ n + 1 ] ; ; If isPrime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Prints a prime pair with given sum ; Generating primes using Sieve ; Traversing all numbers to find first pair ; Driver code
function SieveOfEratosthenes ( n , isPrime ) { isPrime [ 0 ] = isPrime [ 1 ] = false ; for ( let i = 2 ; i <= n ; i ++ ) isPrime [ i ] = true ; for ( let p = 2 ; p * p <= n ; p ++ ) { if ( isPrime [ p ] == true ) { for ( let i = p * p ; i <= n ; i += p ) isPrime [ i ] = false ; } } return false ; } function findPrimePair ( n ) { let isPrime = new Array ( n + 1 ) ; for ( let i = 0 ; i < n + 1 ; i ++ ) { isPrime [ i ] = false ; } SieveOfEratosthenes ( n , isPrime ) ; for ( let i = 0 ; i < n ; i ++ ) { if ( isPrime [ i ] && isPrime [ n - i ] ) { document . write ( i + " " + ( n - i ) ) ; return ; } } } let n = 74 ; findPrimePair ( n ) ;
Count numbers with same first and last digits | Utility method to get first digit of x ; method to return count of numbers with same starting and ending digit from 1 upto x ; get ten - spans from 1 to x ; add 9 to consider all 1 digit numbers ; Find first and last digits ; If last digit is greater than first digit then decrease count by 1 ; Method to return count of numbers with same starting and ending digit between start and end ; Driver code
function getFirstDigit ( x ) { while ( x >= 10 ) x /= 10 ; return x ; } function getCountWithSameStartAndEndFrom1 ( x ) { if ( x < 10 ) return x ; let tens = x / 10 ; let res = tens + 9 ; let firstDigit = getFirstDigit ( x ) ; let lastDigit = x % 10 ; if ( lastDigit < firstDigit ) res -- ; return res ; } function getCountWithSameStartAndEnd ( start , end ) { return getCountWithSameStartAndEndFrom1 ( end ) - getCountWithSameStartAndEndFrom1 ( start - 1 ) ; } let start = 5 , end = 40 ; document . write ( getCountWithSameStartAndEnd ( start , end ) ) ;
Right | Generate all prime numbers less than n . ; Initialize all entries of boolean array as true . A value in isPrime [ i ] will finally be false if i is Not a prime , else true bool isPrime [ n + 1 ] ; ; If isPrime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Returns true if n is right - truncatable , else false ; Generating primes using Sieve ; Checking whether the number remains prime when the last ( right ) digit is successively removed ; Driver program
function sieveOfEratosthenes ( n , isPrime ) { isPrime [ 0 ] = isPrime [ 1 ] = false ; for ( let i = 2 ; i <= n ; i ++ ) isPrime [ i ] = true ; for ( let p = 2 ; p * p <= n ; p ++ ) { if ( isPrime [ p ] == true ) { for ( let i = p * 2 ; i <= n ; i += p ) isPrime [ i ] = false ; } } } function rightTruPrime ( n ) { let isPrime = new Array ( n + 1 ) . fill ( false ) ; sieveOfEratosthenes ( n , isPrime ) ; while ( n != 0 ) { if ( isPrime [ n ] ) n = parseInt ( n / 10 ) ; else return false ; } return true ; } var n = 59399 ; if ( rightTruPrime ( n ) ) document . write ( " " ) ; else document . write ( " " ) ;
Mersenne Prime | Generate all prime numbers less than n . ; Initialize all entries of boolean array as true . A value in prime [ i ] will finally be false if i is Not a prime , else true bool prime [ n + 1 ] ; ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Function to generate mersenne primes lessthan or equal to n ; Create a boolean array " prime [ 0 . . n ] " ; Generating primes using Sieve ; Generate all numbers of the form 2 ^ k - 1 and smaller than or equal to n . ; Checking whether number is prime and is one less then the power of 2 ; Driver Code
function SieveOfEratosthenes ( n , prime ) { for ( let i = 0 ; i <= n ; i ++ ) prime [ i ] = true ; for ( let p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( let i = p * 2 ; i <= n ; i += p ) prime [ i ] = false ; } } } function mersennePrimes ( n ) { let prime = [ ] ; SieveOfEratosthenes ( n , prime ) ; for ( let k = 2 ; ( ( 1 << k ) - 1 ) <= n ; k ++ ) { let num = ( 1 << k ) - 1 ; if ( prime [ ( num ) ] ) document . write ( num + " " ) ; } } let n = 31 ; document . write ( " " + " " + " " + n + " " ) ; mersennePrimes ( n ) ;
Find sum of modulo K of first N natural number | Return sum of modulo K of first N natural numbers . ; Iterate from 1 to N && evaluating and adding i % K . ; Driver Code
function findSum ( N , K ) { let ans = 0 ; for ( let i = 1 ; i <= N ; i ++ ) ans += ( i % K ) ; return ans ; } let N = 10 , K = 2 ; document . write ( findSum ( N , K ) ) ;
Find sum of modulo K of first N natural number | Return sum of modulo K of first N natural numbers . ; Counting the number of times 1 , 2 , . . , K - 1 , 0 sequence occurs . ; Finding the number of elements left which are incomplete of sequence Leads to Case 1 type . ; adding multiplication of number of times 1 , 2 , . . , K - 1 , 0 sequence occurs and sum of first k natural number and sequence from case 1. ; Driver code
function findSum ( N , K ) { let ans = 0 ; let y = N / K ; let x = N % K ; ans = ( K * ( K - 1 ) / 2 ) * y + ( x * ( x + 1 ) ) / 2 ; return ans ; } let N = 10 ; let K = 2 ; document . write ( findSum ( N , K ) ) ;
Smallest number to multiply to convert floating point to natural | Finding GCD of two number ; Returns smallest integer k such that k * str becomes natural . str is an input floating point number ; Find size of string representing a floating point number . ; Below is used to find denominator in fraction form . ; Used to find value of count_after_dot ; To find numerator in fraction form of given number . For example , for 30.25 , numerator would be 3025. ; If there was no dot , then number is already a natural . ; Find denominator in fraction form . For example , for 30.25 , denominator is 100 ; Result is denominator divided by GCD - of - numerator - and - denominator . For example , for 30.25 , result is 100 / GCD ( 3025 , 100 ) = 100 / 25 = 4 ; Driver code
function gcd ( a , b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } function findnum ( str ) { var n = str . length ; var count_after_dot = 0 ; let dot_seen = false ; var num = 0 ; for ( i = 0 ; i < n ; i ++ ) { if ( str . charAt ( i ) != ' ' ) { num = num * 10 + ( str . charAt ( i ) - ' ' ) ; if ( dot_seen == true ) count_after_dot ++ ; } else dot_seen = true ; } if ( dot_seen == false ) return 1 ; var dem = parseInt ( Math . pow ( 10 , count_after_dot ) ) ; return ( dem / gcd ( num , dem ) ) ; } let str = " " ; document . write ( findnum ( str ) ) ;
Find the maximum number of handshakes | Calculating the maximum number of handshake using derived formula . ; Driver Code
function maxHandshake ( n ) { return ( n * ( n - 1 ) ) / 2 ; } let n = 10 ; document . write ( maxHandshake ( n ) ) ;
Count digits in given number N which divide N | Utility function to check divisibility by digit ; ( N [ i ] - '0' ) gives the digit value and form the number ; Function to count digits which appears in N and divide N divide [ 10 ] -- > array which tells that particular digit divides N or not count [ 10 ] -- > counts frequency of digits which divide N ; We initialize all digits of N as not divisible by N ; 1 divides all numbers ; start checking divisibility of N by digits 2 to 9 ; if digit divides N then mark it as true ; Now traverse the number string to find and increment result whenever a digit divides N . ; Driver Code
function divisible ( N , digit ) { let ans = 0 ; for ( let i = 0 ; i < N . length ; i ++ ) { ans = ( ans * 10 + ( N [ i ] - ' ' ) ) ; ans %= digit ; } return ( ans == 0 ) ; } function allDigits ( N ) { let divide = [ ] ; for ( let i = 0 ; i < divide . length ; i ++ ) { divide [ i ] = false ; } divide [ 1 ] = true ; for ( let digit = 2 ; digit <= 9 ; digit ++ ) { if ( divisible ( N , digit ) ) divide [ digit ] = true ; } let result = 0 ; for ( let i = 0 ; i < N . length ; i ++ ) { if ( divide [ N [ i ] - ' ' ] == true ) result ++ ; } return result ; } let N = " " ; document . write ( allDigits ( N ) ) ;
Count numbers which can be constructed using two numbers | Returns count of numbers from 1 to n that can be formed using x and y . ; Create an auxiliary array and initialize it as false . An entry arr [ i ] = true is going to mean that i can be formed using x and y ; x and y can be formed using x and y . ; Initialize result ; Traverse all numbers and increment result if a number can be formed using x and y . ; If i can be formed using x and y ; Then i + x and i + y can also be formed using x and y . ; Increment result ; Driver code
function countNums ( n , x , y ) { arr = Array ( n + 1 ) . fill ( false ) ; if ( x <= n ) arr [ x ] = true ; if ( y <= n ) arr [ y ] = true ; var result = 0 ; for ( i = Math . min ( x , y ) ; i <= n ; i ++ ) { if ( arr [ i ] ) { if ( i + x <= n ) arr [ i + x ] = true ; if ( i + y <= n ) arr [ i + y ] = true ; result ++ ; } } return result ; } var n = 15 , x = 5 , y = 7 ; document . write ( countNums ( n , x , y ) ) ;
Emirp numbers | Function to find reverse of any number ; Sieve method used for generating emirp number ( use of sieve of Eratosthenes ) ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Traverse all prime numbers ; Find reverse a number ; A number is emrip if it is not a palindrome number and its reverse is also prime . ; Mark reverse prime as false so that it 's  not printed again ; Driver code
function reverse ( x ) { var rev = 0 ; while ( x > 0 ) { rev = ( rev * 10 ) + x % 10 ; x = parseInt ( x / 10 ) ; } return rev ; } function printEmirp ( n ) { var prime = Array . from ( { length : n + 1 } , ( _ , i ) => true ) ; for ( p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( i = p * 2 ; i <= n ; i += p ) prime [ i ] = false ; } } for ( p = 2 ; p <= n ; p ++ ) { if ( prime [ p ] ) { var rev = reverse ( p ) ; if ( p != rev && rev <= n && prime [ rev ] ) { document . write ( p + " " + rev + " " ) ; prime [ rev ] = false ; } } } } var n = 100 ; printEmirp ( n ) ;
Abundant Number | Function to calculate sum of divisors ; Note that this loop runs till square root of n ; If divisors are equal , take only one of them ; Otherwise take both ; calculate sum of all proper divisors only ; Function to check Abundant Number ; Return true if sum of divisors is greater than n . ; Driver Code
function getSum ( n ) { let sum = 0 ; for ( let i = 1 ; i <= Math . sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { if ( n / i == i ) sum = sum + i ; else { sum = sum + i ; sum = sum + ( n / i ) ; } } } sum = sum - n ; return sum ; } function checkAbundant ( n ) { return ( getSum ( n ) > n ) ; } let k = checkAbundant ( 12 ) ? " " : " " ; document . write ( k ) ; k = checkAbundant ( 15 ) ? " " : " " ; document . write ( k ) ;
Powerful Number | function to check if the number is powerful ; First divide the number repeatedly by 2 ; If only 2 ^ 1 divides n ( not higher powers ) , then return false ; if n is not a power of 2 then this loop will execute repeat above process ; Find highest power of " factor " that divides n ; If only factor ^ 1 divides n ( not higher powers ) , then return false ; n must be 1 now if it is not a prime numenr . Since prime numbers are not powerful , we return false if n is not 1. ; Driver code to test above methods
function isPowerful ( n ) { while ( n % 2 == 0 ) { let power = 0 ; while ( n % 2 == 0 ) { n /= 2 ; power ++ ; } if ( power == 1 ) return false ; } for ( let factor = 3 ; factor <= Math . sqrt ( n ) ; factor += 2 ) { let power = 0 ; while ( n % factor == 0 ) { n = n / factor ; power ++ ; } if ( power == 1 ) return false ; } return ( n == 1 ) ; } if ( isPowerful ( 20 ) ) document . write ( " " + " " ) ; else document . write ( " " + " " ) ; if ( isPowerful ( 27 ) ) document . write ( " " + " " ) ; else document . write ( " " + " " ) ;
Deficient Number | Function to calculate sum of divisors ; Note that this loop runs till square root of n ; If divisors are equal , take only one of them ; else Otherwise take both ; Function to check Deficient Number ; Check if sum ( n ) < 2 * n ; Driver code to test above methods
function divisorsSum ( n ) { for ( let i = 1 ; i <= ( Math . sqrt ( n ) ) ; i ++ ) { if ( n % i == 0 ) { if ( n / i == i ) { sum = sum + i ; } { sum = sum + i ; sum = sum + ( n / i ) ; } } } return sum ; } function isDeficient ( n ) { return ( divisorsSum ( n ) < ( 2 * n ) ) ; } if ( isDeficient ( 12 ) ) document . write ( " " + " " ) ; else document . write ( " " + " " ) ; if ( isDeficient ( 15 ) ) document . write ( " " + " " ) ; else document . write ( " " + " " ) ;
Harshad ( Or Niven ) Number | Javascript implementation of above approach ; Converting integer to string ; Initialising sum to 0 ; Traversing through the string ; Converting character to int ; Comparing number and sum ; Driver Code ; passing this number to get result function
function checkHarshad ( n ) { let st = String ( n ) let sum = 0 let length = st . length for ( i in st ) { sum = sum + parseInt ( i ) } if ( n % sum == 0 ) { return " " } else { return " " } } let number = 18 document . write ( checkHarshad ( number ) )
Kaprekar Number | Returns true if n is a Kaprekar number , else false ; Count number of digits in square ; Split the square at different points and see if sum of any pair of splitted numbers is equal to n . ; To avoid numbers like 10 , 100 , 1000 ( These are not Karprekar numbers ; Find sum of current parts and compare with n ; compare with original number ; Driver code
function iskaprekar ( n ) { if ( n == 1 ) return true ; let sq_n = n * n ; let count_digits = 0 ; while ( sq_n ) { count_digits ++ ; sq_n = parseInt ( sq_n / 10 ) ; } for ( let r_digits = 1 ; r_digits < count_digits ; r_digits ++ ) { let eq_parts = Math . pow ( 10 , r_digits ) ; if ( eq_parts == n ) continue ; let sum = parseInt ( ( sq_n1 / eq_parts ) + sq_n1 % eq_parts ) ; if ( sum == n ) return true ; } return false ; } document . write ( " " + " " ) ; for ( let i = 1 ; i < 10000 ; i ++ ) if ( iskaprekar ( i ) ) document . write ( i + " " ) ;
Keith Number | Returns true if x is Keith , else false . ; Store all digits of x in a vector " terms " Also find number of digits and store in " n " . ; let n = 0 ; n is number of digits in x ; To get digits in right order ( from MSB to LSB ) ; Keep finding next trms of a sequence generated using digits of x until we either reach x or a number greate than x ; Next term is sum of previous n terms ; When the control comes out of the while loop , either the next_term is equal to the number or greater than it . If next_term is equal to x , then x is a Keith number , else not ; Driver Code
function isKeith ( x ) { let terms = [ ] ; let temp = x ; while ( temp > 0 ) { terms . push ( temp % 10 ) ; temp = parseInt ( temp / 10 ) ; n ++ ; } terms = terms . reverse ( ) ; let next_term = 0 ; let i = n ; while ( next_term < x ) { next_term = 0 ; for ( let j = 1 ; j <= n ; j ++ ) next_term += terms [ i - j ] ; terms . push ( next_term ) ; i ++ ; } return ( next_term == x ) ; } isKeith ( 14 ) ? document . write ( " " ) : document . write ( " " ) ; isKeith ( 12 ) ? document . write ( " " ) : document . write ( " " ) ; isKeith ( 197 ) ? document . write ( " " ) : document . write ( " " ) ;
Check if a number can be expressed as a sum of consecutive numbers | This function returns true if n can be expressed sum of consecutive . ; We basically return true if n is a power of two ; function call
function canBeSumofConsec ( n ) { return ( ( ( n & ( n - 1 ) ) != 0 ) && n != 0 ) ; } let n = 15 ; document . write ( canBeSumofConsec ( n ) ? " " : " " ) ;
Even Fibonacci Numbers Sum | Returns sum of even Fibonacci numbers which are less than or equal to given limit . ; Initialize first two even prime numbers and their sum ; calculating sum of even Fibonacci value ; get next even value of Fibonacci sequence ; If we go beyond limit , we break loop ; Move to next even number and update sum ; Function call
function evenFibSum ( limit ) { if ( limit < 2 ) return 0 ; let ef1 = 0 , ef2 = 2 ; let sum = ef1 + ef2 ; while ( ef2 <= limit ) { let ef3 = 4 * ef2 + ef1 ; if ( ef3 > limit ) break ; ef1 = ef2 ; ef2 = ef3 ; sum += ef2 ; } return sum ; } let limit = 400 ; document . write ( evenFibSum ( limit ) ) ;
Find numbers with K odd divisors in a given range | Utility function to check if number is perfect square or not ; Utility Function to return count of divisors of a number ; Note that this loop runs till square root ; If divisors are equal , count it only once ; Otherwise print both ; Function to calculate all divisors having exactly k divisors between a and b ; Initialize result ; calculate only for perfect square numbers ; check if number is perfect square or not ; total divisors of number equals to k or not ; Driver Code
function isPerfect ( n ) { var s = parseInt ( ( Math . sqrt ( n ) ) ) ; return ( s * s == n ) ; } function divisorsCount ( n ) { var count = 0 ; for ( var i = 1 ; i <= parseInt ( Math . sqrt ( n ) ) + 1 ; i ++ ) { if ( n % i == 0 ) { if ( parseInt ( n / i ) == i ) count += 1 ; else count += 2 ; } } return count ; } function kDivisors ( a , b , k ) { var count = 0 ; for ( var i = a ; i <= b ; i ++ ) { if ( isPerfect ( i ) ) { if ( divisorsCount ( i ) == k ) { count ++ ; } } } return count ; } var a = 2 , b = 49 , k = 3 ; document . write ( kDivisors ( a , b , k ) ) ;
Nth Even Fibonacci Number | Function which return nth even fibonnaci number ; calculation of Fn = 4 * ( Fn - 1 ) + Fn - 2 ; Driver Code
function evenFib ( n ) { if ( n < 1 ) return n ; if ( n == 1 ) return 2 ; return ( ( 4 * evenFib ( n - 1 ) ) + evenFib ( n - 2 ) ) ; } let n = 7 ; document . write ( evenFib ( n ) ) ;
Repeated subtraction among two numbers | Returns count of steps before one of the numbers become 0 after repeated subtractions . ; If y divides x , then simply return x / y . ; Else recur . Note that this function works even if x is smaller than y because in that case first recursive call exchanges roles of x and y . ; Driver code
function countSteps ( x , y ) { if ( x % y == 0 ) return Math . floor ( x / y ) ; return Math . floor ( x / y ) + countSteps ( y , x % y ) ; } let x = 100 , y = 19 ; document . write ( countSteps ( x , y ) ) ;
Common Divisors of Two Numbers | Map to store the count of each prime factor of a ; Function that calculate the count of each prime factor of a number ; Function to calculate all common divisors of two given numbers a , b -- > input integer numbers ; Find count of each prime factor of a ; stores number of common divisors ; Find the count of prime factors of b using distinct prime factors of a ; Prime factor of common divisor has minimum cnt of both a and b ; Driver code
let ma = new Map ( ) ; function primeFactorize ( a ) { for ( let i = 2 ; i * i <= a ; i += 2 ) { let cnt = 0 ; while ( a % i == 0 ) { cnt ++ ; a = parseInt ( a / i , 10 ) ; } ma . set ( i , cnt ) ; } if ( a > 1 ) { ma . set ( a , 1 ) ; } } function commDiv ( a , b ) { primeFactorize ( a ) ; let res = 1 ; ma . forEach ( ( values , keys ) => { let cnt = 0 ; let key = keys ; let value = values ; while ( b % key == 0 ) { b = parseInt ( b / key , 10 ) ; cnt ++ ; } res *= ( Math . min ( cnt , value ) + 1 ) ; } ) return res ; } let a = 12 , b = 24 ; document . write ( commDiv ( a , b ) ) ;
Count number of solutions of x ^ 2 = 1 ( mod p ) in given range | Javascript program to count number of values that satisfy x ^ 2 = 1 mod p where x lies in range [ 1 , n ] ; Initialize result ; Traverse all numbers smaller than given number p . Note that we don 't traverse from 1 to n,  but 1 to p ; If x is a solution , then count all numbers of the form x + i * p such that x + i * p is in range [ 1 , n ] ; The largest number in the form of x + p * i in range [ 1 , n ] ; Add count of numbers of the form x + p * i . 1 is added for x itself . ; Driver code
function findCountOfSolutions ( n , p ) { let ans = 0 ; for ( let x = 1 ; x < p ; x ++ ) { if ( ( x * x ) % p == 1 ) { let last = x + p * ( n / p ) ; if ( last > n ) last -= p ; ans += ( ( last - x ) / p + 1 ) ; } } return ans ; } let n = 10 ; let p = 5 ; document . write ( findCountOfSolutions ( n , p ) ) ;
Happy Number | method return true if n is Happy Number numSquareSum method is given in below detailed code snippet
let st = new Set ( ) ; while ( 1 ) { n = numSquareSum ( n ) ; if ( n == 1 ) return true ; if ( st . has ( n ) ) return false ; st . add ( n ) ; } }
Kaprekar Constant | This function checks validity of kaprekar ' s ▁ constant . ▁ It ▁ returns ▁ kaprekar ' s constant for any four digit number " n " such that all digits of n are not same . ; Store current n as previous number ; Get four digits of given number ; Sort all four dgits in ascending order And giet in the form of number " asc " ; Get all four dgits in descending order in the form of number " desc " ; Get the difference of two numbers ; If difference is same as previous , we have reached kaprekar 's constant ; Else recur ; A wrapper over kaprekarRec ( ) ; Trying few four digit numbers , we always get 6174
function kaprekarRec ( n , prev ) { if ( n == 0 ) return 0 ; prev = n ; var digits = Array . from ( { length : 4 } , ( _ , i ) => 0 ) ; for ( i = 0 ; i < 4 ; i ++ ) { digits [ i ] = n % 10 ; n = parseInt ( n / 10 ) ; } digits . sort ( ) ; var asc = 0 ; for ( i = 0 ; i < 4 ; i ++ ) asc = asc * 10 + digits [ i ] ; digits . sort ( ) ; var desc = 0 ; for ( i = 3 ; i >= 0 ; i -- ) desc = desc * 10 + digits [ i ] ; var diff = Math . abs ( asc - desc ) ; if ( diff == prev ) return diff ; return kaprekarRec ( diff , prev ) ; } function kaprekar ( n ) { var prev = 0 ; return kaprekarRec ( n , prev ) ; } document . write ( kaprekar ( 1000 ) + " " ) ; document . write ( kaprekar ( 1112 ) + " " ) ; document . write ( kaprekar ( 9812 ) + " " ) ;