so I am writing a function to get biggest divisor,
and I am running it in VScode using command
$ -node script.js
it is logging nothing, what am I missing?
here is the content of script.js :
let LFfinder = num => {
let result = num;
for (let i = num - 1; i > 1 && result === num; i--) {
if (num % i === 0) {
result = i;
return result;
}
if (!i) {
return result;
}
}
console.log(result);
};
LFfinder(15);
You are writing console.log() at the place where control is not reaching as per your logic. Try writing before you return the value
let LFfinder = num => {
let result = num;
for (let i = num - 1; i > 1 && result === num; i--) {
if (num % i === 0) {
result = i;
console.log(result);
return result;
}
if (!i) {
console.log(result);
return result;
}
}
};
LFfinder(15)
You don't need to return in the loop. Because of return the console.log statement is never reached. And the else part is not required. This will work:
let LFfinder = num => {
let result = num;
for (let i = num - 1; i > 1 && result === num; i--) {
if (num % i === 0) {
result = i;
break;
}
}
console.log(result);
};
LFfinder(15);
LFfinder(19);
LFfinder(200);
Note that you don't need to loop through till end. The first instance you find is the greatest, so save further iteration with break.
Also, it's better that the function returns a value instead of logging the answer.
let LFfinder = num => {
let result = num;
for (let i = num - 1; i > 1 && result === num; i--) {
if (num % i === 0) {
result = i;
break;
}
}
return result;
};
console.log(LFfinder(15));
console.log(LFfinder(19));
console.log(LFfinder(200));
its working fine, please check the link, i've tried
https://repl.it/#HarshSrivastav1/playgroundams
Related
I'm trying to come up with a function that gives me a "factorial" of a number but in a different way.
For example:
15! = 15*14/13+12-11*10/9... and so on.
I tried doing this by first creating an array and, then, a loop to get to the result. But it doesn't work as expected. The result expected from the code below is 13.
function createList(n) {
let input = n
let list = [input]
for(i = input-1; i >= 1; i--) {
list.push(i)
}
return list
}
function factorialDiff() {
let elements = createList(12)
var res = elements.shift()
while(elements.length >= 1) {
if(elements.length == 0) {
return res
}
res *= elements.shift()
if(elements.length == 0) {
return res
}
res /= elements.shift()
if(elements.length == 0) {
return res
}
res += elements.shift()
if(elements.length == 0) {
return res
}
res -= elements.shift()
if(elementos.length == 0) {
return res
}
}
return res
}
console.log(factorialDiff())
``
`
This is what your code is doing:
console.log(((((12*11)/10+9-8)*7/6+5-4)*3)/2+1);
In math the convention is to solve multiplication/division first and plus/minus second in this order. However, the code you did is solving the operations from left to right.
For example:
console.log(12*11/10+9-8*7/6+5-4*3/2+1); // returns 12.86
console.log(((((12*11)/10+9-8)*7/6+5-4)*3)/2+1); // returns 27.35 just like your function does
If your expected behavior is the first line, the following function should solve your problem:
function factorialDiff() {
const elements = createList(12);
let res1 = elements.shift();
let res2 = elements.shift();
let res3 = elements.shift();
let res = (res1*res2/res3)
while(elements.length >= 1) {
res += elements.shift();
if(elements.length == 0) {
return res;
}
res1 = elements.shift();
if(elements.length == 0) {
return res*res1;
}
res2 = elements.shift();
if(elements.length == 0) {
return res*res1/res2;
}
res3 = elements.shift();
res -= (res1*res2/res3);
if(elements.length == 0) {
return res;
}
}
return res;
}
Is this what you looking for?
function myFactorial(num) {
var result = num;
operatorNum = 0;
for(i = num - 1; i >= 1; i--){
if(operatorNum % 4 == 0){ // "*"
result = result * i;
}else if (operatorNum % 4 == 1){ // "/"
result = result / i;
}else if (operatorNum % 4 == 2){ // "+"
result = result + i;
}else{ // "-"
result = result - i;
}
operatorNum++;
}
return result;
}
console.log(myFactorial(4)); // logs 7
I need to write a prime factorisation function that returns an object whose keys are a prime factor and values are the exponents of the corresponding prime factors. E.g.
console.log(primeFactorisation(4)) // { 2: 2 }
console.log(primeFactorisation(6)) // { 2: 1, 3: 1 }
My code so far is below but I'm stuck. Any help much appreciated.
const primeFactorisation = (num) => {
let result = {};
for (let i = 2; i < num; i++) {
if (num % i === 0) {
result[i] = i;
num /= i;
}
}
return result
}
When a number is found, increment it on the result object instead of assigning i to the result object.
You also need a nested loop to keep testing for the number until it no longer divides evenly, and you also need i <= num, not i < num, so that the last factor is caught:
const primeFactorisation = (num) => {
let result = {};
for (let i = 2; i <= num; i++) {
while (num % i === 0) {
result[i] = (result[i] || 0) + 1;
num /= i;
}
}
return result
}
console.log(
primeFactorisation(6),
primeFactorisation(4),
);
I am trying to solve a problem where I am required to loop through an array of arrays, each of which contains a list of numbers that together make up a credit card number. I've been asked to use the Luhn algorithm to validate these numbers, working from the rightmost number in each array to the leftmost. I came up with a function that successfully returns true or false for each array correctly (I know in advance that 5 are valid and 5 are false while a remaining 5 are not known). However, when I then try to loop through the array containing all these arrays, calling the function on them each in turn, the program hangs for ages and finally returns a long list of trues, far longer than the 15 results I expect. My code is below, validateCred seems to work for each card number individually, but findValidCards does not. I can't see why this is happening, can anyone enlighten me?
const validateCred = arr => {
const resultArray = [];
let index = (arr.length) - 1;
if ((index % 2) != 0) {
for (i = index; i >= 0; i--) {
if ((i % 2) == 0) {
let doubled = arr[i] * 2;
if (doubled > 9) {
let numToUnshift = doubled - 9;
resultArray.unshift(numToUnshift);
} else {
resultArray.unshift(doubled);
};
} else {
resultArray.unshift(arr[i]);
};
};
} else {
for (i = index; i >= 0; i--) {
if ((i % 2) != 0) {
let doubled = arr[i] * 2;
if (doubled > 9) {
let numToUnshift = doubled - 9;
resultArray.unshift(numToUnshift);
} else {
resultArray.unshift(doubled);
};
} else {
resultArray.unshift(arr[i]);
};
};
};
const reducer = (acc, curr) => acc + curr;
let sum = resultArray.reduce(reducer);
if ((sum % 10) == 0) {
return true;
} else {
return false;
};
}
const findInvalidCards = array => {
let resultArray = [];
for (i = 0; i < array.length; i++) {
let card = array[i];
let result = validateCred(card);
console.log(result);
};
};
My code
When i use word cat the function doesn't return anything.
function reverse(str) {
let result = '';
let i = str.length-1;
while ( i < 0) {
result = result + str[i];
i--;
}
return result;
}// END```
You need to take length and the check for greater or equal than zero for the loop.
function reverse(str) {
let result = '';
let i = str.length - 1;
while (i >= 0) {
result = result + str[i];
i--;
}
return result;
}
console.log(reverse('cat'));
A slightly shorter approach with decrementing and check in one.
function reverse(str) {
let result = '',
i = str.length;
while (i--) result = result + str[i];
return result;
}
console.log(reverse('cat'));
Use str.length; instead of str.legth-1;
legth is not a function. The function in length
function reverse(str) {
let result = '';
let i = str.length;
while (i--) {
result = result + str[i];
}
return result;
}
console.log(reverse('ellipsis'))
You had a typo and a logic error:
function reverse(str) {
let result = '';
let i = str.length - 1; // str.length
while (i >= 0) { // greater than equal to :)
result = result + str[i];
i--;
}
return result;
}
You could use reduce
const reverse = str => str.split('').reduce((result, char) => char + result);
console.log(reverse('cat'));
This should return the nth prime (n being the number given by the user). It works fine for the first few numbers (1 returns 2, 2 returns 3, 3 returns 5) but when 5 is given, it returns 9 which isn't prime (it should be 11). This happens with other numbers as well above this (7 returns 15 when it should be 17).
The 'document' stuff is to do with HTML where I'm getting the userValue and to display the prime number.
function isPrime(value) {
for(var i = 2; i < value; i++) {
if(value % i === 0) {
return false;
}
}
return value > 1;
}
function generatePrime() {
var userValue = document.getElementById("inputValue").value;
var iter = 1;
var returnValue = 2;
//checks for an integer
if (parseInt(userValue) === parseFloat(userValue)) {
//checks if the user inputted a value above 0
if (userValue > 0) {
//loops to find the correct prime
while (iter < userValue) {
if (isPrime(returnValue)) {
returnValue += 1;
iter += 1;
}
if (!isPrime(returnValue)) {
returnValue += 1;
}
}
}
else {
returnValue = "That is not a number above 0!";
}
}
else {
returnValue = "That is not a number!";
}
document.getElementById("returnValue").innerHTML = returnValue;
}
I need help with making this return the correct number.
Try this one.
function nextPrime(value) {
if (value > 2) {
var i, q;
do {
i = 3;
value += 2;
q = Math.floor(Math.sqrt(value));
while (i <= q && value % i) {
i += 2;
}
} while (i <= q);
return value;
}
return value === 2 ? 3 : 2;
}
function generatePrime() {
var userValue = document.getElementById("inputValue").value;
var value = 0, result = [];
for (var i = 0; i < userValue; i++) {
value = nextPrime(value);
result.push(value);
}
document.getElementById("returnValue").innerHTML = result[userValue-1];
}
<!DOCTYPE html>
<html>
<head>
<script>
</script>
</head>
<body>
Input value: <input type="text" name="inputValue" id="inputValue"/>
<button onclick="generatePrime()">Prime number</button>
<div id="returnValue">Test: </div>
</body>
</html>
You can try something like this:
function getNthPrimeNumber(n){
var count = 0;
var num = 2;
while(count++ != n){
num = getNextPrimeNumber(num);
}
return num;
}
function getNextPrimeNumber(n){
for(var i = ++n; i< n*n; i++){
if(isPrime(i)) return i
}
return 0;
}
function isPrime(n){
for(var i = 2; i< n; i++)
if (n%i===0)
return false;
return true;
}
console.log(getNthPrimeNumber(0))
console.log(getNthPrimeNumber(2))
console.log(getNthPrimeNumber(5))
You could reduce the range of iteration for function isPrime() :
function isPrime(value) {
for(var i = 2; i < Math.sqrt(value) + 1; i++) {
if(value % i === 0) {
return false;
}
}
return value > 1;
}
The following is based on Bhaskara Arani's submission, but I added caching.
Note: I also threw in an addition condition to check for palindrome.
This check can be removed via:
while (i <= root && value % i /* && isPalindrome(value) */)
const main = () => {
for (let i = 15; i >= 0; i--) {
console.log(`Palindrome Prime ${i + 1} = ${generatePrime(i)}`);
}
};
const cachedPrimes = [];
const generatePrime = (index) => {
let value = cachedPrimes[cachedPrimes.length - 1] ?? 0;
for (let i = cachedPrimes.length; i <= index; i++) {
value = nextPrime(value);
cachedPrimes.push(value);
}
return cachedPrimes[index];
};
const nextPrime = (value) => {
if (value > 2) {
let i, root;
do {
i = 3; value += 2; root = ~~Math.sqrt(value);
while (i <= root && value % i && isPalindrome(value)) {
i += 2;
}
} while (i <= root);
return value;
}
return value === 2 ? 3 : 2;
};
const isPalindrome = (n) => n === reverse(n);
const reverse = n => +`${n}`.split('').reverse().join('');
main();
.as-console-wrapper { top: 0; max-height: 100% !important; }