I'm trying to write an if / else statement in my computeDigit() function so that when executed, looks if resultFromDivision has a remainder of 0 and if so, then return that number ( Number(n) ) as a factor of num. I also was trying to figure out how to continue to run the algorithm even after the statement, if resultFromDivsion has a remainder of 0, is found to be true. That way I could save it and store it to an array as other factors of num. My intended output for selectedNumber = 7337 should be returns 29 253 as factors of 7337
I've tried modifying the code many different ways but I either get undefined (like currently) from my factor() function or my resultFromDivision is a decimal and is saying it's a factor of num when it is not from my computeDigit() function. Also, I've tried rearranging the if/else statements, flipping my equals and not equals to. Etc. I'm not sure how to rewrite the code in a way that will get it to run as intended.
Another issue with my code is the factor() function... I wrote weird code in an attempt to get the javascript code to run the computeDigit() function for the variables a,b,c,d. Then return all the results. But it doesn't seem to work and also returns undefined. The if statement for that used to be:
if (lastDigit === 7) {
digitArray = [9, 3, 7]
return computeDigit(digitArray, selectedNumber);
computeDigit():
const computeDigit = (arr, num) => {
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j <= num; j++) {
const n = `${j}` + `${arr[i]}`; // JOIN Operation
const resultFromDivision = num / Number(n);
if (resultFromDivision !== num && resultFromDivision % Number(n) === 0) {
if (
resultFromDivision !== 1 &&
resultFromDivision === Math.floor(resultFromDivision)
) {
return `${n} is a factor of ${num}`;
} else if (resultFromDivision === 1) {
return `${n} is a prime?`; //
}
}
if (
resultFromDivision !== Math.floor(resultFromDivision) &&
resultFromDivision % n === 0
) {
return `${n} is a factor of ${num} ${resultFromDivision}.`;
}
}
}
};
factor()
const factor = (selectedNumber) => {
if (typeof selectedNumber != "number") {
throw new Error("Must be a natural number or an integer.");
}
let a;
let b;
let c;
let d;
const lastDigit = parseInt(
`${selectedNumber}`[`${selectedNumber}`.length - 1]
);
if (lastDigit === 7) {
a = [1];
b = [3];
c = [7];
d = [9];
return computeDigit(a && b && c && d, selectedNumber);
}
};
console.log(factor(7337));
Sorry if this is a two-part problem, but I think most of the issue is coming from computeDigit(). If anyone could offer some help/solutions I'd really appreciate it!!
Aucun commentaire:
Enregistrer un commentaire