codeparrot/xlcost-text-to-code huggingface dataset:
Largest palindromic number in an array | Function to check if n is palindrome ; Find the appropriate divisor to extract the leading digit ; If first and last digits are not same then return false ; Removing the leading and trailing digits from the number ; Reducing divisor by a factor of 2 as 2 digits are dropped ; Function to find the largest palindromic number ; If a palindrome larger than the currentMax is found ; Return the largest palindromic number from the array ; Driver code ; Print required answer
function isPalindrome ( n ) { var divisor = 1 ; while ( parseInt ( n / divisor ) >= 10 ) divisor *= 10 ; while ( n != 0 ) { var leading = parseInt ( n / divisor ) ; var trailing = n % 10 ; if ( leading != trailing ) return false ; n = parseInt ( ( n % divisor ) / 10 ) ; divisor = parseInt ( divisor / 100 ) ; } return true ; } function largestPalindrome ( A , n ) { var currentMax = - 1 ; for ( var i = 0 ; i < n ; i ++ ) { if ( A [ i ] > currentMax && isPalindrome ( A [ i ] ) ) currentMax = A [ i ] ; } return currentMax ; } var A = [ 1 , 232 , 54545 , 999991 ] ; var n = A . length ; document . write ( largestPalindrome ( A , n ) ) ;
Reduce the array to a single element with the given operation | Function to return the final element ; Driver code
function getFinalElement ( n ) { let finalNum ; for ( finalNum = 2 ; finalNum * 2 <= n ; finalNum *= 2 ) ; return finalNum ; } let N = 12 ; document . write ( getFinalElement ( N ) ) ;
Sum of elements in an array having prime frequency | Function to create Sieve to check primes ; False here indicates that it is not prime ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p , set them to non - prime ; Function to return the sum of elements in an array having prime frequency ; Map is used to store element frequencies ; Traverse the map using iterators ; Count the number of elements having prime frequencies ; Driver code
function SieveOfEratosthenes ( prime , p_size ) { prime [ 0 ] = false ; prime [ 1 ] = false ; for ( let p = 2 ; p * p <= p_size ; p ++ ) { if ( prime [ p ] ) { for ( let i = p * 2 ; i <= p_size ; i += p ) prime [ i ] = false ; } } } function sumOfElements ( arr , n ) { let prime = new Array ( n + 1 ) ; prime . fill ( true ) SieveOfEratosthenes ( prime , n + 1 ) ; let i , j ; let m = new Map ( ) ; for ( i = 0 ; i < n ; i ++ ) { if ( m . has ( arr [ i ] ) ) m . set ( arr [ i ] , m . get ( arr [ i ] ) + 1 ) ; else m . set ( arr [ i ] , 1 ) ; } let sum = 0 ; for ( let it of m ) { if ( prime [ it [ 1 ] ] ) { sum += ( it [ 0 ] ) ; } } return sum ; } let arr = [ 5 , 4 , 6 , 5 , 4 , 6 ] ; let n = arr . length ; document . write ( sumOfElements ( arr , n ) ) ;
Sum of all odd length palindromic numbers within the range [ L , R ] | Function that returns true if the given number is a palindrome ; Here we are generating a new number ( reverse_num ) * by reversing the digits of original input number ; If the original input number ( num ) is equal to * to its reverse ( reverse_num ) then its palindrome * else it is not . ; Function that returns true if the given number is of odd length ; Function to return the sum of all odd length palindromic numbers within the given range ; if number is palindrome and of odd length ; Driver code
function isPalindrome ( num ) { let reverse_num = 0 , remainder , temp ; temp = num ; while ( temp != 0 ) { remainder = temp % 10 ; reverse_num = reverse_num * 10 + remainder ; temp = Math . floor ( temp / 10 ) ; } if ( reverse_num == num ) { return true ; } return false ; } function isOddLength ( num ) { let count = 0 ; while ( num > 0 ) { num = Math . floor ( num / 10 ) ; count ++ ; } if ( count % 2 != 0 ) { return true ; } return false ; } function sumOfAllPalindrome ( L , R ) { let sum = 0 ; if ( L <= R ) for ( let i = L ; i <= R ; i ++ ) { if ( isPalindrome ( i ) && isOddLength ( i ) ) { sum += i ; } } return sum ; } let L = 110 , R = 1130 ; document . write ( sumOfAllPalindrome ( L , R ) ) ;
Number of ways to arrange a word such that all vowels occur together | Factorial of a number ; Calculating ways for arranging consonants ; Ignore vowels ; Calculating ways for arranging vowels ; Function to count total no . of ways ; Count vowels and consonant ; Total no . of ways ; Driver code
function fact ( n ) { let f = 1 ; for ( let i = 2 ; i <= n ; i ++ ) f = f * i ; return f ; } function waysOfConsonants ( size1 , freq ) { let ans = fact ( size1 ) ; for ( let i = 0 ; i < 26 ; i ++ ) { if ( i == 0 i == 4 i == 8 i == 14 i == 20 ) continue ; else ans = Math . floor ( ans / fact ( freq [ i ] ) ) ; } return ans ; } function waysOfVowels ( size2 , freq ) { return Math . floor ( fact ( size2 ) / ( fact ( freq [ 0 ] ) * fact ( freq [ 4 ] ) * fact ( freq [ 8 ] ) * fact ( freq [ 14 ] ) * fact ( freq [ 20 ] ) ) ) ; } function countWays ( str ) { let freq = new Array ( 200 ) ; for ( let i = 0 ; i < 200 ; i ++ ) freq [ i ] = 0 ; for ( let i = 0 ; i < str . length ; i ++ ) freq [ str [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] ++ ; let vowel = 0 , consonant = 0 ; for ( let i = 0 ; i < str . length ; i ++ ) { if ( str [ i ] != ' ' && str [ i ] != ' ' && str [ i ] != ' ' && str [ i ] != ' ' && str [ i ] != ' ' ) consonant ++ ; else vowel ++ ; } return waysOfConsonants ( consonant + 1 , freq ) * waysOfVowels ( vowel , freq ) ; } let str = " " ; document . write ( countWays ( str ) ) ;
Sum of Fibonacci Numbers with alternate negatives | Computes value of first fibonacci numbers and stores their alternate sum ; Initialize result ; Add remaining terms ; For even terms ; For odd terms ; Return the alternating sum ; Get n ; Find the alternating sum
function calculateAlternateSum ( n ) { if ( n <= 0 ) return 0 ; var fibo = Array ( n + 1 ) . fill ( 0 ) ; fibo [ 0 ] = 0 ; fibo [ 1 ] = 1 ; var sum = Math . pow ( fibo [ 0 ] , 2 ) + Math . pow ( fibo [ 1 ] , 2 ) ; for ( i = 2 ; i <= n ; i ++ ) { fibo [ i ] = fibo [ i - 1 ] + fibo [ i - 2 ] ; if ( i % 2 == 0 ) sum -= fibo [ i ] ; else sum += fibo [ i ] ; } return sum ; } var n = 8 ; document . write ( " " + n + " " + calculateAlternateSum ( n ) ) ;
Find nth Term of the Series 1 2 2 4 4 4 4 8 8 8 8 8 8 8 8 ... | Function that will return nth term ; Get n ; Get the value ; Get n ; Get the value
function getValue ( n ) { let i = 0 , k = 1 ; while ( i < n ) { i = i + k ; k = k * 2 ; } return parseInt ( k / 2 ) ; } let n = 9 ; document . write ( getValue ( n ) + " " ) ; n = 1025 ; document . write ( getValue ( n ) + " " ) ;
Construct a frequency array of digits of the values obtained from x ^ 1 , x ^ 2 , ... ... . . , x ^ n | Function that traverses digits in a number and modifies frequency count array ; Array to keep count of digits ; Traversing through x ^ 1 to x ^ n ; For power function , both its parameters are to be in double ; calling countDigits function on x ^ i ; Printing count of digits 0 - 9 ; Driver code
function countDigits ( val , arr ) { while ( val > 0 ) { let digit = val % 10 ; arr [ digit ] ++ ; val = Math . floor ( val / 10 ) ; } return ; } function countFrequency ( x , n ) { let freq_count = new Array ( 10 ) ; for ( let i = 0 ; i < 10 ; i ++ ) { freq_count [ i ] = 0 ; } for ( let i = 1 ; i <= n ; i ++ ) { let val = Math . pow ( x , i ) ; countDigits ( val , freq_count ) ; } for ( let i = 0 ; i <= 9 ; i ++ ) { document . write ( freq_count [ i ] + " " ) ; } } let x = 15 , n = 3 ; countFrequency ( x , n ) ;
Number of values of b such that a = b + ( a ^ b ) | function to return the number of solutions ; check for every possible value ; Driver Code
function countSolutions ( a ) { let count = 0 ; for ( let i = 0 ; i <= a ; i ++ ) { if ( a == ( i + ( a ^ i ) ) ) count ++ ; } return count ; } let a = 3 ; document . write ( countSolutions ( a ) ) ;
Number of values of b such that a = b + ( a ^ b ) | Javascript program to find the number of values of b such that a = b + ( a ^ b ) ; Function to return the number of solutions ; Driver Code
function bitCount ( n ) { let count = 0 ; while ( n != 0 ) { count ++ ; n &= ( n - 1 ) ; } return count ; } function countSolutions ( a ) { let count = bitCount ( a ) ; count = Math . pow ( 2 , count ) ; return count ; } let a = 3 ; document . write ( countSolutions ( a ) ) ;
Sum of Area of all possible square inside a rectangle | Function to calculate the sum of area of all possible squares that comes inside the rectangle ; Square with max size possible ; calculate total square of a given size ; calculate area of squares of a particular size ; total area ; increment size ; Driver Code
function calculateAreaSum ( l , b ) { var size = 1 ; var maxSize = Math . min ( l , b ) ; var totalArea = 0 ; for ( var i = 1 ; i <= maxSize ; i ++ ) { var totalSquares = ( l - size + 1 ) * ( b - size + 1 ) ; var area = totalSquares * size * size ; totalArea += area ; size ++ ; } return totalArea ; } var l = 4 , b = 3 ; document . write ( calculateAreaSum ( l , b ) ) ;
Hyperfactorial of a number | function to calculate the value of hyperfactorial ; initialise the val to 1 ; returns the hyperfactorial of a number ; Driver code
function boost_hyperfactorial ( num ) { let val = 1 ; for ( let i = 1 ; i <= num ; i ++ ) { val = val * Math . pow ( i , i ) ; } return val ; } let num = 5 ; document . write ( boost_hyperfactorial ( num ) ) ;
Hyperfactorial of a number | function to calculate the value of hyperfactorial ; initialise the val to 1 ; 1 ^ 1 * 2 ^ 2 * 3 ^ 3. . . . ; returns the hyperfactorial of a number ; Driver code
function boost_hyperfactorial ( num ) { var val = 1 ; for ( var i = 1 ; i <= num ; i ++ ) { for ( var j = 1 ; j <= i ; j ++ ) { val *= i ; } } return val ; } var num = 5 ; document . write ( boost_hyperfactorial ( num ) ) ;
Subtract 1 without arithmetic operators | JavaScript code to subtract one from a given number ; Flip all the set bits until we find a 1 ; flip the rightmost 1 bit ; Driver program to test above functions
function subtractOne ( x ) { let m = 1 ; while ( ! ( x & m ) ) { x = x ^ m ; m <<= 1 ; } x = x ^ m ; return x ; } document . write ( subtractOne ( 13 ) ) ;
Find the mean vector of a Matrix | Javascript program to find mean vector of given matrix ; Function to find mean vector ; Loop to traverse each column ; To calculate mean of each row ; to store sum of elements of a column ; Driver code
var rows = 3 ; var cols = 3 ; function meanVector ( mat ) { document . write ( " " ) ; for ( var i = 0 ; i < rows ; i ++ ) { var mean = 0.00 ; var sum = 0 ; for ( var j = 0 ; j < cols ; j ++ ) sum += mat [ j ] [ i ] ; mean = sum / rows ; document . write ( mean + " " ) ; } document . write ( " " ) ; } var mat = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] ; meanVector ( mat ) ;
Hoax Number | Function to find distinct prime factors of given number n ; n is odd at this point , since it is no longer divisible by 2. So we can test only for the odd numbers , whether they are factors of n ; Check if i is prime factor ; This condition is to handle the case when n is a prime number greater than 2 ; Function to calculate sum of digits of distinct prime factors of given number n and sum of digits of number n and compare the sums obtained ; Distinct prime factors of n are being stored in vector pf ; If n is a prime number , it cannot be a hoax number ; Finding sum of digits of distinct prime factors of the number n ; Finding sum of digits in current prime factor pf [ i ] . ; Finding sum of digits of number n ; Comparing the two calculated sums ; Driver Method
function primeFactors ( n ) { var res = [ ] ; if ( n % 2 == 0 ) { while ( n % 2 == 0 ) n = parseInt ( n / 2 ) ; res . push ( 2 ) ; } for ( var i = 3 ; i <= Math . sqrt ( n ) ; i = i + 2 ) { if ( n % i == 0 ) { while ( n % i == 0 ) n = parseInt ( n / i ) ; res . push ( i ) ; } } if ( n > 2 ) res . push ( n ) ; return res ; } function isHoax ( n ) { var pf = primeFactors ( n ) ; if ( pf [ 0 ] == n ) return false ; var all_pf_sum = 0 ; for ( var i = 0 ; i < pf . length ; i ++ ) { var pf_sum ; for ( pf_sum = 0 ; pf [ i ] > 0 ; pf_sum += pf [ i ] % 10 , pf [ i ] = parseInt ( pf [ i ] / 10 ) ) ; all_pf_sum += pf_sum ; } var sum_n ; for ( sum_n = 0 ; n > 0 ; sum_n += n % 10 , n = parseInt ( n / 10 ) ) ; return sum_n == all_pf_sum ; } var n = 84 ; if ( isHoax ( n ) ) document . write ( " " ) ; else document . write ( " " ) ;
Primality Test | Set 5 ( Using Lucas | Function to find out first n terms ( considering 4 as 0 th term ) of Lucas - Lehmer series . ; the 0 th term of the series is 4. ; create an array to store the terms . ; compute each term and add it to the array . ; print out the terms one by one . ; Driver Code
function LucasLehmer ( n ) { let current_val = 4 ; let series = [ ] ; series . push ( current_val ) ; for ( let i = 0 ; i < n ; i ++ ) { current_val = ( current_val * current_val ) - 2 ; series . push ( current_val ) ; } for ( let i = 0 ; i <= n ; i ++ ) { document . write ( " " + i + " " + series [ i ] + " " ) ; } } let n = 5 ; LucasLehmer ( n ) ;
Modular multiplicative inverse from 1 to n | A naive method to find modular multiplicative inverse of ' a ' under modulo ' prime ' ; Driver code
function modInverse ( a , prime ) { a = a % prime ; for ( let x = 1 ; x < prime ; x ++ ) if ( ( a * x ) % prime == 1 ) return x ; return - 1 ; } function printModIverses ( n , prime ) { for ( let i = 1 ; i <= n ; i ++ ) document . write ( modInverse ( i , prime ) + " " ) ; } let n = 10 ; let prime = 17 ; printModIverses ( n , prime ) ;
Convert to number with digits as 3 and 8 only | function for minimum operation ; remainder and operations count ; count digits not equal to 3 or 8 ; driver function
function minOp ( num ) { var rem ; var count = 0 ; while ( num ) { rem = num % 10 ; if ( ! ( rem == 3 rem == 8 ) ) count ++ ; num = parseInt ( num / 10 ) ; } return count ; } var num = 234198 ; document . write ( " " + minOp ( num ) ) ;
Biggest integer which has maximum digit sum in range from 1 to n | Function to calculate the sum of digits of a number . ; Returns the maximum number with maximum sum of digits . ; Initializing b as 1 and initial max sum to be of n ; Iterates from right to left in a digit ; While iterating this is the number from from right to left ; Calls the function to check if sum of cur is more then of ans ; Reduces the number to one unit less ; Driver Code
function sumOfDigits ( a ) { var sum = 0 ; while ( a != 0 ) { sum += a % 10 ; a = parseInt ( a / 10 ) ; } return sum ; } function findMax ( x ) { var b = 1 , ans = x ; while ( x != 0 ) { var cur = ( x - 1 ) * b + ( b - 1 ) ; if ( sumOfDigits ( cur ) > sumOfDigits ( ans ) || ( sumOfDigits ( cur ) == sumOfDigits ( ans ) && cur > ans ) ) ans = cur ; x = parseInt ( x / 10 ) ; b *= 10 ; } return ans ; } var n = 521 ; document . write ( findMax ( n ) ) ;
Interquartile Range ( IQR ) | Function to give index of the median ; Function to calculate IQR ; Index of median of entire data ; Median of first half ; Median of second half ; IQR calculation ; Driver Code
function median ( a , l , r ) { var n = r - l + 1 ; n = parseInt ( ( n + 1 ) / 2 ) - 1 ; return parseInt ( n + l ) ; } function IQR ( a , n ) { a . sort ( ( a , b ) => a - b ) ; var mid_index = median ( a , 0 , n ) ; var Q1 = a [ median ( a , 0 , mid_index ) ] ; var Q3 = a [ mid_index + median ( a , mid_index + 1 , n ) ] ; return ( Q3 - Q1 ) ; } var a = [ 1 , 19 , 7 , 6 , 5 , 9 , 12 , 27 , 18 , 2 , 15 ] ; var n = a . length ; document . write ( IQR ( a , n ) ) ;
Largest palindromic number in an array | function for sorting ; Function to check if n is palindrome ; Find the appropriate divisor to extract the leading digit ; If first and last digits are not same then return false ; Removing the leading and trailing digits from the number ; Reducing divisor by a factor of 2 as 2 digits are dropped ; Function to find the largest palindromic number ; Sort the array ; If number is palindrome ; If no palindromic number found ; print required answer
function ssort ( a , n ) { var i , j , min , temp ; for ( i = 0 ; i < n - 1 ; i ++ ) { min = i ; for ( j = i + 1 ; j < n ; j ++ ) if ( a [ j ] < a [ min ] ) min = j ; temp = a [ i ] ; a [ i ] = a [ min ] ; a [ min ] = temp ; } } function isPalindrome ( n ) { var divisor = 1 ; while ( parseInt ( n / divisor ) >= 10 ) divisor *= 10 ; while ( n != 0 ) { var leading = parseInt ( n / divisor ) ; var trailing = n % 10 ; if ( leading != trailing ) return false ; n = parseInt ( ( n % divisor ) / 10 ) ; divisor = parseInt ( divisor / 100 ) ; } return true ; } function largestPalindrome ( A , n ) { ssort ( A , A . length ) ; for ( var i = n - 1 ; i >= 0 ; -- i ) { if ( isPalindrome ( A [ i ] ) ) return A [ i ] ; } return - 1 ; } var A = [ 1 , 232 , 54545 , 999991 ] ; var n = A . length ; document . write ( largestPalindrome ( A , n ) ) ;
Sum of the multiples of two numbers below N | Function to return the sum of all the integers below N which are multiples of either A or B ; If i is a multiple of a or b ; Driver code
function findSum ( n , a , b ) { let sum = 0 ; for ( let i = 0 ; i < n ; i ++ ) if ( i % a == 0 i % b == 0 ) sum += i ; return sum ; } let n = 10 ; let a = 3 ; let b = 5 ; document . write ( findSum ( n , a , b ) ) ;
Subtract 1 without arithmetic operators | Driver program to test above functions
function subtractOne ( x ) { return ( ( x << 1 ) + ( ~ x ) ) ; } document . write ( ( subtractOne ( 13 ) ) ) ;
Pell Number | calculate nth pell number ; Driver Code
function pell ( n ) { if ( n <= 2 ) return n ; return 2 * pell ( n - 1 ) + pell ( n - 2 ) ; } let n = 4 ; document . write ( pell ( n ) ) ;
Finding LCM of more than two ( or array ) numbers without using GCD | Returns LCM of arr [ 0. . n - 1 ] ; Find the maximum value in arr [ ] ; Initialize result ; Find all factors that are present in two or more array elements . var x = 2 ; Current factor . ; To store indexes of all array elements that are divisible by x . ; If there are 2 or more array elements that are divisible by x . ; Reduce all array elements divisible by x . ; Then multiply all reduced array elements ; Driver code
function LCM ( arr , n ) { var max_num = 0 ; for ( var i = 0 ; i < n ; i ++ ) if ( max_num < arr [ i ] ) max_num = arr [ i ] ; var res = 1 ; while ( x <= max_num ) { var indexes = [ ] ; for ( var j = 0 ; j < n ; j ++ ) if ( arr [ j ] % x == 0 ) indexes . push ( j ) ; if ( indexes . length >= 2 ) { for ( var j = 0 ; j < indexes . length ; j ++ ) arr [ indexes [ j ] ] = arr [ indexes [ j ] ] / x ; res = res * x ; } else x ++ ; } for ( var i = 0 ; i < n ; i ++ ) res = res * arr [ i ] ; return res ; } var arr = [ 1 , 2 , 3 , 4 , 5 , 10 , 20 , 35 ] ; var n = arr . length ; document . write ( LCM ( arr , n ) + " " ) ;
Find politeness of a number | Function to find politeness ; sqrt ( 2 * n ) as max length will be when the sum starts from 1 which follows the equation n ^ 2 - n - ( 2 * sum ) = 0 ; Driver Code
function politness ( n ) { let count = 0 ; for ( let i = 2 ; i <= Math . sqrt ( 2 * n ) ; i ++ ) { let a ; if ( ( 2 * n ) % i != 0 ) continue ; a = 2 * n ; a = Math . floor ( a / i ) ; a -= ( i - 1 ) ; if ( a % 2 != 0 ) continue ; a = Math . floor ( a / 2 ) ; if ( a > 0 ) { count ++ ; } } return count ; } let n = 90 ; document . write ( " " + n + " " + politness ( n ) + " " ) ; n = 15 ; document . write ( " " + n + " " + politness ( n ) ) ;
Program for Goldbachâ €™ s Conjecture ( Two Primes with given Sum ) | Javascript program to implement Goldbach 's conjecture ; Array to store all prime less than and equal to 10 ^ 6 ; Utility function for Sieve of Sundaram ; In general Sieve of Sundaram , produces primes smaller than ( 2 * x + 2 ) for a number given number x . Since we want primes smaller than MAX , we reduce MAX to half . This array is used to separate numbers of the form i + j + 2 * i * j from others where 1 <= i <= j ; Main logic of Sundaram . Mark all numbers which do not generate prime number by doing 2 * i + 1 ; Since 2 is a prime number ; Print other primes . Remaining primes are of the form 2 * i + 1 such that marked [ i ] is false . ; Function to perform Goldbach 's conjecture ; Return if number is not even or less than 3 ; Check only upto half of number ; find difference by subtracting current prime from n ; Search if the difference is also a prime number ; Express as a sum of primes ; Finding all prime numbers before limit ; Express number as a sum of two primes
let MAX = 10000 ; let primes = new Array ( ) ; function sieveSundaram ( ) { let marked = new Array ( parseInt ( MAX / 2 ) + 100 ) . fill ( false ) ; for ( let i = 1 ; i <= ( Math . sqrt ( MAX ) - 1 ) / 2 ; i ++ ) for ( let j = ( i * ( i + 1 ) ) << 1 ; j <= MAX / 2 ; j = j + 2 * i + 1 ) marked [ j ] = true ; primes . push ( 2 ) ; for ( let i = 1 ; i <= MAX / 2 ; i ++ ) if ( marked [ i ] == false ) primes . push ( 2 * i + 1 ) ; } function findPrimes ( n ) { if ( n <= 2 n % 2 != 0 ) { document . write ( " " ) ; return ; } for ( let i = 0 ; primes [ i ] <= n / 2 ; i ++ ) { let diff = n - primes [ i ] ; if ( primes . includes ( diff ) ) { document . write ( primes [ i ] + " " + diff + " " + n + " " ) ; return ; } } } sieveSundaram ( ) ; findPrimes ( 4 ) ; findPrimes ( 38 ) ; findPrimes ( 100 ) ;
k | A function to generate prime factors of a given number n and return k - th prime factor ; Find the number of 2 's that  divide k ; n must be odd at this point . So we can skip one element ( Note i = i + 2 ) ; While i divides n , store i and divide n ; This condition is to handle the case where n is a prime number greater than 2 ; Driver code
function kPrimeFactor ( n , k ) { while ( n % 2 == 0 ) { k -- ; n = n / 2 ; if ( k == 0 ) return 2 ; } for ( let i = 3 ; i <= Math . sqrt ( n ) ; i = i + 2 ) { while ( n % i == 0 ) { if ( k == 1 ) return i ; k -- ; n = n / i ; } } if ( n > 2 && k == 1 ) return n ; return - 1 ; } let n = 12 , k = 3 ; document . write ( kPrimeFactor ( n , k ) + " " ) ; n = 14 ; k = 3 ; document . write ( kPrimeFactor ( n , k ) ) ;
k | Javascript program to find k - th prime factor using Sieve Of Eratosthenes . This program is efficient when we have a range of numbers . ; Using SieveOfEratosthenes to find smallest prime factor of all the numbers . For example , if MAX is 10 , s [ 2 ] = s [ 4 ] = s [ 6 ] = s [ 10 ] = 2 s [ 3 ] = s [ 9 ] = 3 s [ 5 ] = 5 s [ 7 ] = 7 ; Create a boolean array " prime [ 0 . . MAX ] " and initialize all entries in it as false . ; Initializing smallest factor equal to 2 for all the even numbers ; For odd numbers less then equal to n ; s ( i ) for a prime is the number itself ; For all multiples of current prime number ; i is the smallest prime factor for number " i * j " . ; Function to generate prime factors and return its k - th prime factor . s [ i ] stores least prime factor of i . ; Keep dividing n by least prime factor while either n is not 1 or count of prime factors is not k . ; To keep track of count of prime factors ; Divide n to find next prime factor ; s [ i ] is going to store prime factor of i .
var MAX = 10001 ; function sieveOfEratosthenes ( s ) { prime = Array . from ( { length : MAX + 1 } , ( _ , i ) => false ) ; for ( i = 2 ; i <= MAX ; i += 2 ) s [ i ] = 2 ; for ( i = 3 ; i <= MAX ; i += 2 ) { if ( prime [ i ] == false ) { s [ i ] = i ; for ( j = i ; j * i <= MAX ; j += 2 ) { if ( prime [ i * j ] == false ) { prime [ i * j ] = true ; s [ i * j ] = i ; } } } } } function kPrimeFactor ( n , k , s ) { while ( n > 1 ) { if ( k == 1 ) return s [ n ] ; k -- ; n /= s [ n ] ; } return - 1 ; } var s = Array . from ( { length : MAX + 1 } , ( _ , i ) => 0 ) ; sieveOfEratosthenes ( s ) ; var n = 12 , k = 3 ; document . write ( kPrimeFactor ( n , k , s ) + " " ) ; n = 14 ; k = 3 ; document . write ( kPrimeFactor ( n , k , s ) ) ;