JS simple math task (raising an inputed number to a power) - javascript

I have a task in js. My program should take a number from a user and put it into power that is also inserted. I have coped with positive powers but the algorithm for negative ones always gives a positive answer and after putting an option for a zero power every variant somehow returns -1; Please help me find an error.
function powX(x, pow) {
x = +prompt('Insert a number: ');
pow = +prompt('Insert a power: ');
var result;
if (x > 0) {
var result = x;
for (i = 1; i < pow; i++) {
result *= x;
}
}
if (x < 0) {
var result = x;
for (i = 1; i < Math.abs(pow); i++) {
result /= x;
}
} else {
result = 1;
}
return result;
}
console.log(powX());

There are few mistakes in the code:
You should use else-if instead of if in your second block.
You should check pow instead of x
You are not using var or let with i so it will become global variable. Use let or var
You are using var again inside your if blocks but variables declared with var have function scope so it will not throw error. But with let it will break your code. Don't redeclare result again and again.
function powX(x, pow) {
x = +prompt('Insert a number: ');
pow = +prompt('Insert a power: ');
var result;
if (pow > 0) {
result = x;
for (let i = 1; i < pow; i++) {
result *= x;
}
}
else if (pow < 0) {
result = x;
for (let i = 0; i <= Math.abs(pow); i++) {
result /= x;
}
} else {
result = 1;
}
return result;
}
console.log(powX());
You don't need two loops one to divide and other using multiply. Just calculate the result just by multiplying and at the end multiply the result with x or divide it based on condition.
function powX(x, pow) {
x = +prompt('Insert a number: ');
pow = +prompt('Insert a power: ');
if(pow === 0) return 1;
var result = x;
for (let i = 1; i < Math.abs(pow); i++) {
result *= x;
}
return pow < 0 ? (x/result/x) : result;
}
console.log(powX());

Use an else if for your second condition, otherwise, its else block will always be executed for x > 0, setting your result to 1.
function powX(x, pow) {
x = +prompt('Insert a number: ');
pow = +prompt('Insert a power: ');
var result;
if (x > 0) {
result = x;
for (i = 1; i < pow; i++) {
result *= x;
}
}
else if (x < 0) {
result = x;
for (i = 1; i < Math.abs(pow); i++) {
result /= x;
}
} else {
result = 1;
}
return result;
}
console.log(powX());
Also, it'll look better if you remove the re-declaration of result in the if and else if blocks. It won't affect your output but still.
Note: As #ASDFGerte correctly pointed out in the comments, OP's code has other flaws, but I think this still answers his main concern and actual question.

Related

Fibronacci sequence spitting wrong number

I have created a function that sumbs up all odd fibronacci numbers up to a given number, and for the most part it works all for except one number. For example sumFibs(10) should return 10 becuz all Fib #s <= 10 are 1,1,3 and 5.
If I do sumFibs(75024); I get 135721 instead of the expected value is 60696. For every other number it works perfectly and am scratching my head to solve it
function sumFibs(num) {
let thunderAss = [];
let currDmp = 0;
let nxtRmp = 1;
var pushNxt = 0;
// push into array
for (let x = 0; x < num; x++) {
if (x <= 1) {
console.log("lets go");
thunderAss.push(1); // 2l almond milk
} else {
thunderAss.push(thunderAss[x - 1] + thunderAss[x - 2]);
console.log(x, " x is factor");
}
}
console.log(thunderAss);
let cuntNuts = 0;
for (let x = 0; x < num; x++) {
if (cuntNuts < num) {
if (thunderAss[x] % 2 == 0) {} else {
cuntNuts += thunderAss[x];
}
} else {
break;
}
}
console.log("CN: ", cuntNuts);
return cuntNuts;
}
sumFibs(75024); // 60696 but 135721
sumFibs(4);
The condition if (cuntNuts < num) is wrong. cuntNuts is the sum of fibonacci numbers, not the fibonacci number itself. So you're stopping when the sum reaches n, not summing all the odd numbers up to n.
You should be comparing thunderAss[x] with num. And it should be <= if that number should be included in the total.
You can also put this condition into the for loop header rather than adding it as a separate check in the body.
function sumFibs(num) {
let thunderAss = [];
let currDmp = 0;
let nxtRmp = 1;
var pushNxt = 0;
// push into array
for (let x = 0; x < num; x++) {
if (x <= 1) {
console.log("lets go");
thunderAss.push(1); // 2l almond milk
} else {
thunderAss.push(thunderAss[x - 1] + thunderAss[x - 2]);
console.log(x, " x is factor");
}
}
console.log(thunderAss);
let cuntNuts = 0;
for (let x = 0; thunderAss[x] <= num; x++) {
if (thunderAss[x] % 2 == 0) {} else {
cuntNuts += thunderAss[x];
}
}
console.log("CN: ", cuntNuts);
return cuntNuts;
}
sumFibs(75024); // 60696 but 135721
sumFibs(4);
You are adding the num first Fibonacci numbers instead of the Fibonacci numbers less than or equal to num.
In my solution here, I do the correct thing and get the correct answer:
function* fibonacci()
{
let x = 0;
let y = 1;
while (true) {
yield x;
[x, y] = [y, x+y];
}
}
function sum_odd_fibonacci(max)
{
const fib_seq = fibonacci();
let s = 0;
let n;
while ( (n=fib_seq.next().value) <= max) {
if (n % 2 == 1) {
s += n;
}
}
return s;
}
console.log(sum_odd_fibonacci(75024));

How do I print the return value of a function?

I'm trying to print the return value of a function but I just can't seem to do it. I keep getting undefined for the last line.
let count = 0;
function product(num){
let result = 1;
strNum = num.toString()
strNumArr = strNum.split("")
if(strNum.length === 1){
return count;
}
for(let i = 0; i< strNum.length; i++){
result *= parseInt(strNumArr[i])
}
count++;
//console.log(count)
product(result)
}
let bool = product(39);
console.log(product(39));
I know I'm missing something basic, but I don't know what it is.
If I understand what you are trying to achieve correctly, here is a working version of your code.
function product(num){
let result = 1;
strNum = num.toString()
strNumArr = strNum.split("")
if(strNum.length === 1){
return num;
}
for(let i = 0; i< strNum.length; i++){
result *= parseInt(strNumArr[i])
}
return result;
}
console.log(product(39)); // should return 27
console.log(product(5)); // should return 5
console.log(product(234)); // should return 24
You should return the result after you are done with the loop.
By the way the same can be achieved with a one liner. For example
function product(num) {
return Array.from(String(num).split('')).reduce((c,p) => p * c, 1)
}
Replace product(result) to return product(result). This way if the function calls itself it returns the value generated in the nested function call.
let count = 0;
function product(num){
let result = 1;
strNum = num.toString()
strNumArr = strNum.split("")
if(strNum.length === 1){
return count;
}
for(let i = 0; i< strNum.length; i++){
result *= parseInt(strNumArr[i])
}
count++;
//console.log(count)
return product(result)
}
let bool = product(39);
console.log(product(39));

Using forEach Loop Generating prime number in Javascript between 1 to 50 [duplicate]

This question already has answers here:
Check Number prime in JavaScript
(47 answers)
Closed 2 years ago.
Here's my code but my answer is not that which i want..
Please Check This and give me a solution to get prime number using Foreach Loop b/w 1-50
Thanks In Advance :)
function isPrime(num) {
for ( var i = 2; i < num; i++ ) {
if ( num % i === 0 ) {
return false;
}
}
return true;
}
var txt = "";
function shown(n) {
var arr = [2];
arr.forEach(myFunction);
document.getElementById("foreach").innerHTML = txt;
// document.getElementById('forLoop').innerHTML = arr; // use arr result on your own
}
function myFunction(arr, index, array) {
var i;
var arr = [2];
if ( isPrime(i) ) {
arr.push(i);
}
txt += arr + "<br>";
}
shown(50);
This is probably a too-advanced answer for a homework of this level, but technically it follows the rules (use Array.forEach) and it works.
The primes() generates new primes based on previous primes. So it won't test the reminder of all integers, thus more effecient. There are several arrow function uses, too, to keep things short. If you indeed use this answer, please try to read the relevant documentations and learn:
Iterators and Generators
Arrow function expressions
for...of
Template literals
Seriously, try to think step-by-step. That's how you learn anything.
function* primes() {
const previous = [];
for (let i = 2; true; i++) {
let isPrime = true;
for (let p of previous) {
if (i % p === 0) {
isPrime = false;
break;
}
}
if (isPrime) {
previous.push(i);
yield i;
}
}
}
function* takeUntil(cb, iter) {
for (let val of iter) {
if (cb(val)) {
return;
}
yield val;
}
}
function showArrayIn(arr, container) {
arr.forEach(p => container.innerHTML += `${p},<br/>`); // technically, we used Array.forEach.
}
showArrayIn(
// get the prime number array declarativly
Array.from(takeUntil(n => n >= 50, primes())),
// show in the container specified
document.getElementById("results")
);
Primes:
<div id="results"></div>
function primeFactorsTo(max)
{
var store = [], i, j, primes = [];
for (i = 2; i <= max; ++i)
{
if (!store [i])
{
primes.push(i);
for (j = i << 1; j <= max; j += i)
{
store[j] = true;
}
}
}
return primes;
}
console.log(primeFactorsTo(5));
console.log(primeFactorsTo(15));
I Think so this is the correct answer which i deserve..
It is code lover short and aggressive
function primes(limit)
{
var prime=[], i=1;
while (++i < limit+1) prime.reduce((a,c)=>(i%c)*a,1) && prime.push(i);
prime.unshift(2);
return prime;
}
[50].forEach(n=>document.getElementById('foreach').innerHTML=(`${primes(n)}`));
Consider the following example.
function isPrime(num) {
if (num === 1) {
return false;
} else if (num === 2) {
return true;
} else {
for (var x = 2; x < num; x++) {
if (num % x === 0) {
return false;
}
}
return true;
}
}
function shown(n) {
var list = [];
for (var i = 1; i <= n; i++) {
list.push(i);
}
list.slice().reverse().forEach(function(n, k, o) {
if (!isPrime(n)) {
list.splice(o.length - 1 - k, 1);
}
});
document.getElementById("show").innerHTML = list;
}
shown(50);
Prime: <p id="show"></p>

Why Javascript console.log result is NaN when I tried Repeat a string a specified times

function repeatS(srr, num) {
if (num <= 0) {
return "";
}
var result = "";
for (var i = 0; i < num; i++) {
result = +srr;
}
return result;
}
console.log(repeatS("ahfidhfd", 3));
strong text
Here is my question, the result is Nan, anyone knows what might be the problem here...
result = +srr;
should be
result += srr;
You use an unary plus + for converting a string to a number, but you need to assign the value to the left hand variable.
function repeatS(srr, num) {
if (num <= 0) {
return "";
}
var result = "";
for (var i = 0; i < num; i++) {
result += srr;
}
return result;
}
console.log(repeatS("ahfidhfd", 3));

Simple function to check if an array is consecutive

I am trying to write a simple function that will test if a an array is consecutive but for some reason it does not work. This is a small part of an angular JS app if that's relevant.
return function isConsecArray(arr){
var i;
var y = (arr.length);
for (i=0; i < y; i += 1){
if (parseInt(arr[i])+1 !== parseInt(arr[i+1]))
{
return false;
}
}
return true;
When reaching the last element, i.e. i=y-1, it compares arr[i] with arr[i+1], which is undefined. You need to iterate up to arr.length-1, i.e.:
...
for (i=1; i < y-1; i += 1) { / NOTE THE y-1 LIMIT
...
You could write it like this:
function isConsecArray(arr) {
var previous = arr[0];
var i;
var y = (arr.length);
if (y > 1) {
for (i=1; i < y; i += 1) {
if (parseInt(arr[i]) -1 !== parseInt(previous)) {
return false;
}
previous = arr[i];
}
}
return true;
}
JSFiddle: http://jsfiddle.net/dq1kccvk/

Categories