Sum All Primes Below a Given Number | Intermediate Javascript Algorithm | Recursion - javascript

Question
A prime number is a whole number greater than 1 with exactly two divisors: 1 and itself. For example, 2 is a prime number because it is only divisible by 1 and 2. In contrast, 4 is not prime since it is divisible by 1, 2 and 4.
Rewrite sumPrimes so it returns the sum of all prime numbers that are less than or equal to num.
My Attempt
const isPrime = a => {
for(let i = 2; i < a; i++)
if(num % i === 0) return false;
return a > 1;
}
function sumPrimes(num, total = []) {
let numVar = num;
let n = total.reduce((aggregate, item)=>{
return aggregate + item;
}, 0);
if(n > numVar){
return n;
}
for(let i = 1; i <= numVar; i++){
if(isPrime(i)== true){
total.push(i);
}
}
return sumPrimes(num, total);
}
sumPrimes(10);
The Problem
It says: 'Num is not defined'
I am not sure if there are other errors.
My Question
Please could you help me find the error, and fix the code to solve the algorithm?

This was a simple syntax error identified by #Jonas Wilms (upvote him in the comment above :))!
By replacing the 'a' with 'num' the function was fixed.
const isPrime = a => {
for(let i = 2; i < a; i++)
if(a % i === 0) return false;
return a > 1;
}
function sumPrimes(num, total = []) {
let numVar = num;
let n = total.reduce((aggregate, item)=>{
return aggregate + item;
}, 0);
if(n > numVar){
return n;
}
for(let i = 1; i <= numVar; i++){
if(isPrime(i)== true){
total.push(i);
}
}
return sumPrimes(num, total);
}
console.log(sumPrimes(10));

this simple function may help you,
function isPrime(num) {
for (var i = 2; i < num; i++)
if (num % i === 0) return false;
return num > 1;
}
function sumPrimes(num) {
let tot = 0;
for (let i = 0; i < num; i++)
if (isPrime(i))
tot += i;
return tot;
}
console.log(sumPrimes(10));

Related

Check Digit Sum Javascript- recursion [duplicate]

This question already has answers here:
Adding digits from a number, using recursivity - javascript
(6 answers)
Closed 8 months ago.
Looking for Javascript solution in recursion to get the sum of all digits in number until single digit come as result
For example, for the number is "55555" the sum of all digits is 25. Because this is not a single-digit number, 2 and 5 would be added, and the result, 7.
I tried the below solution based on the algorithm.
function getSum(n) {
let sum = 0;
while(n > 0 || sum > 9)
{
if(n == 0)
{
n = sum;
sum = 0;
}
sum += n % 10;
n /= 10;
}
return sum;
}
console.log(getSum("55555"));
This would kind of work, but I'm almost sure there's a beautiful one-line solution which I just don't see yet.
function singleDigitSum(str) {
str = [...str].reduce((acc, c) => { return Number(c) + acc }, 0)
while (str.toString().length > 1) {
str = singleDigitSum(str.toString());
}
return str
}
console.log(singleDigitSum("55555"))
Explanation:
As a first step in your function you reassign to the parameter passed to the function the result of a reducer function which sums up all numbers in your String. To be able to use Array.prototype.reduce() function, I'm spreading your str into an array using [...str].
Then, for as often as that reducer returns a value with more than one digit, rinse and repeat. When the while loop exits, the result is single digit and can be returned.
function checSumOfDigit(num, sum = "0") {
if (num.length == 1 && sum.length !== 1) {
return checSumOfDigit(Number(sum) + Number(num) + "", "0");
} else if (num.length == 1) {
return Number(sum) + Number(num);
}
num = num.split("")
sum = Number(sum) + Number(num.pop());
return checSumOfDigit(num.join(""), sum + "")
}
console.log(checSumOfDigit("567"));
console.log(checSumOfDigit("123"));
console.log(checSumOfDigit("55555"));
this code might be help you
If you need a recursion try this one
function CheckDigitSum(number) {
let nums = number.split('');
if (nums.length > 1) {
let sum = 0;
for (let i = 0; i < nums.length; i++) {
sum += Number(nums[i]);
}
return CheckDigitSum(sum.toString());
} else {
return parseInt(nums[0], 10);
}
}
Here you go:
function createCheckDigit(num) {
var output = Array.from(num.toString());
var sum = 0;
if (Array.isArray(output) && output.length) {
for ( i=0; i < output.length; i++){
sum = sum + parseInt(output[i]);
}
if ((sum/10) >= 1){
sum = createCheckDigit(sum);
}
}
return sum;
}
This can be calculated by recursive function.
function createCheckDigit(membershipId) {
// Write the code that goes here.
if(membershipId.length > 1){
var dgts = membershipId.split('');
var sum = 0;
dgts.forEach((dgt)=>{
sum += Number(dgt);
});
//console.log('Loop 1');
return createCheckDigit(sum + '');
}
else{
//console.log('Out of Loop 1');
return Number(membershipId);
}
}
console.log(createCheckDigit("5555555555"));
function checkid(num) {
let sum = 0;
let s = String(num);
for (i = 0; i < s.length; i++) {
sum = sum + Number(s[i]);
}
if(String(sum).length >= 2) return checkid(sum)
else return sum;
}
console.log(checkid(55555);

javascript - functions and equations confusion

var number = prompt('Input a number!');
var n = number;
function getList() {
for (var n = 1; n <= 17; n++) {
if (n % 3 == 0 || n % 5 == 0)
console.log (n);
}
}
console.log(getList());
console.log((n*(n+1))/2);
//equation for summation: (n*(n+1))/2
I'm trying to return the sum of numbers divisible by 3 or 5 up to 17. So far, it half-works; it lists all the numbers, but I can't find a way to return the sum.
I have the equation for summation, but I can't find a way to put it in so that it works. How do you get the equation to reference the list instead of referencing the inputted number?
The answer is supposed to be 60. Any clue? Thanks!
var sum = 0;
for (var n = 1; n <= 17; n++) {
if (n % 3 === 0 || n % 5 === 0)
sum += n;
}
console.log(sum);
Use a variable to add the numbers and return it after for loop.
Below it the exapmle.
function getList() {
var sum = 0;
for (var n = 1; n <= 17; n++) {
if (n % 3 == 0 || n % 5 == 0) {
sum += n;
}
}
return sum;
}
console.log(getList());
Two things:
Just return the sum from your getList function
Make sure your prompt input is converted to integer otherwise it will be treated as a string and your n*(n+1)/2 will be wrong
var number = parseInt(prompt('Input a number!'));
var n = number;
function getList() {
var sum = 0;
for (var n = 1; n <= 17; n++) {
if (n % 3 == 0 || n % 5 == 0) {
console.log (n);
sum += n;
}
}
return sum;
}
console.log(getList());
console.log(n, (n*(n+1))/2);
If you want an equation :)
function sumOfNumbersDivisibleBy3Or5(n) {
const by3 = Math.floor(n/3),
by5 = Math.floor(n/5),
by3And5 = Math.floor(n/3/5);
return 3*by3*(by3+1)/2 + 5*by5*(by5 + 1)/2 - 3*5*by3And5*(by3And5 + 1)/2
}
console.log(sumOfNumbersDivisibleBy3Or5(17))
var number = prompt('Input a number!');
function getList() {
var sum = 0;
for (var n = 1; n <= number; n++) {
if (n % 3 == 0 || n % 5 == 0)
sum+=n;
}
return sum;
}
console.log(getList());
it will return sum of all the number which is divisible by 3 or 5 in between 1 and entered number

Finding sequence of prime numbers with JS

I have to get a sequence of prime numbers. But my code does not work. How is it possible to fix it?
var num1 = parseInt(prompt('Enter a number'));
var num2 = parseInt(prompt('Enter a number'));
var num3 = 0;
function primeSeq(num1, num2) {
var b = 1;
var c = '';
if (num1 > num2) {
num3 = num2;
num2 = num1;
num1 = num3;
}
for (var i = num1; i < num2; i++) {
for (var j = 2; j < i; j++) {
if (i % j == 0) {
b++;
}
if (b <= 1) {
c += i + ' ';
}
}
}
return c;
}
alert(primeSeq(num1, num2));
I guess you wanted something like this
var num1 = parseInt(prompt('Enter a number'));
var num2 = parseInt(prompt('Enter a number'));
var num3 = 0;
if (num1 > num2) {
num3 = num2;
num2 = num1;
num1 = num3;
}
function primeSeq(num1, num2) {
var b;
var c = '';
for (var i = num1; i < num2; i++) {
b = 1;
for (var j = 2; j < i; j++) {
if (i % j === 0) {
b++;
}
}
if (b === 1) {
c += i + ' ';
}
}
return c;
}
alert(primeSeq(num1, num2));
So in short, b should reset to 1 on every new prime candidate (i loop) and check of b should be outside of inner (j) loop.
Please note that there are more optimal algorithms.
The lot easier way is to use a sieve system, if a number is divisible by another prime number it is not a prime. You can write a function like this:
function primes(max) {
let primes = [2];
for (let i = 3; i <= max; i++) {
let found = true;
for (let j = 0; j < primes.length; j++) {
if (i % primes[j] == 0) found = false;
}
if (found) primes.push(i);
}
return primes;
}
Explanation
What you know by default is that 2 is a prime, so you start at 3. You don't want to exeed the max, that is the i <= max statement. Assume it is a prime, then search in the array if it is divisible by primes you found before, if that is the case, set found to false.
Now check if is was found, push is to the array and return the primes.
Here is bit more optimized algorithm:
function primeSeq(num1, num2) {
var primes = [];
var isPrime;
var j;
var results = [];
for (var i = 2; i < num2; i++) {
isPrime = true;
j = 0;
while (j < primes.length) {
if (i % primes[j] === 0) {
isPrime = false;
break;
}
j++;
}
if (isPrime) {
primes.push(i);
if (i >= num1) {
results.push(i);
}
}
}
return results.join(' ');
}
In order for number to be prime it must not be dividable with all the smaller primes, so we are generating an array of primes to check upon.
There is a theory also that every prime bigger than 3 has a following form:
6k+1 or 6k-1
So this would simplify it bit more.
Try this one
<input ng-model="range" type="number" placeholder="Enter the range">
<button ng-click="findPrimeNumber(range)">
$scope.findPrimeNumber=function(range){
var tempArray=[];
for(var i=0;i<=range;i++){
tempArray.push(i)
}
var primenumbers= tempArray.filter((number) => {
for (var i = 2; i <= Math.sqrt($scope.range); i++) {
if (number % i === 0) return false;
}
return true;
});
console.log(primenumbers);
}

Factorialize a Number

I'm taking the freecodecamp course one of the exercises it's to create a Factorialize function, I know there is several ways to do it just not sure what this one keeps returning 5
function factorialize(num) {
var myMax = num;
var myCounter = 1;
var myTotal = 0;
for (i = 0; i>= myMax; i++) {
num = myCounter * (myCounter + 1);
myCounter++;
}
return num;
}
factorialize(5);
This is a recursive solution of your problem:
function factorialize(num) {
if(num <= 1) {
return num
} else {
return num * factorialize(num-1)
}
}
factorialize(5)
This is the iterative solution:
function factorialize(num) {
var cnt = 1;
for (var i = 1; i <= num ; i++) {
cnt *= i;
}
return cnt;
}
factorialize(5)
with argument 5, it will return the 5! or 120.
To answer your question, why your function is returning 5:
Your function never reaches the inner part of the for-loop because your testing if i is greater than myMax instead of less than.
So you are just returning your input parameter which is five.
But the loop does not calculate the factorial of num, it only multiplies (num+1) with (num+2);
My solution in compliance with convention for empty product
function factorializer(int) {
if (int <= 1) {
return 1;
} else {
return int * factorializer(int - 1);
}
}
Here is another way to solve this challenge and I know it is neither the shortest nor the easiest but it is still a valid way.
function factorialiaze(num){
var myArr = []; //declaring an array.
if(num === 0 || num === 1){
return 1;
}
if (num < 0){ //for negative numbers.
return "N/A";
}
for (var i = 1; i <= num; i++){ // creating an array.
myArr.push(i);
}
// Reducing myArr to a single value via .reduce:
num = myArr.reduce(function(a,b){
return a * b;
});
return num;
}
factorialiaze(5);
Maybe you consider another approach.
This solution features a very short - cut to show what is possible to get with an recursive style and a implicit type conversion:
function f(n) { return +!~-n || n * f(n - 1); }
+ convert to number
! not
~ not bitwise
- negative
function f(n) { return +!~-n || n * f(n - 1); }
var i;
for (i = 1; i < 20; i++) {
console.log(f(i));
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
Try this function
const factorialize = (num) => num === 0 ? 1 : num * factorialize(num-1)
Use it like this:
factorialize(5) // returns 120
Try this :
function factorialize(num) {
var value = 1;
if(num === 1 || num ===0) {
return value;
} else {
for(var i = 1; i<num; i++) {
value *= i;
}
return num * value;
}
}
factorialize(5);
// My solution
const factorialize = num => {
let newNum = 1;
for (let i = 1; i <= num; i++) {
newNum *= i
}
return newNum;
}
I love syntactic sugar, so
let factorialize = num => num <= 1 ? num : num * factorialize(num -1)
factorialize(5)

JavaScript Function Arrays

How would I use a function that returns the sum of a given array while getting the sum of the even numbers and sum the odd numbers? I'm not understanding how that is done. Can someone please explain a little more in depth?
Here is my entire code:
function main()
{
var evenNum = 0;
//need a total Even count
var oddNum = 0;
//need a total Odd count
var counter = 1;
var num = 0;
function isOdd(x) {
if ((num % 2) == 0)
{
return false;
}
else
{
return true;
}
}
function isEven(x) {
if ((num % 2) == 0)
{
return false;
}
else
{
return true;
}
}
for (counter = 1; counter <= 100; counter++)
{
num = Math.floor(1 + Math.random() * (100-1));
var total = 0;
for(var j = 0; j < length; j++)
total += a[j];//Array?
console.log(num);
console.log("The count of even number is " + evenNum);
console.log("The count of odd number is " + oddNum);
return 0;
}
main()
If I understand your question correctly, you need a function that returns two values, one for the sum of even numbers and one for the sum of odd numbers. It's not clear if you use even/odd referring to the index of the array or the values in array.
In both cases you can return an object that contains both values:
function sum(array) {
var evenSum = 0;
var oddSum = 0;
...calculate...
var res = {};
res.evenSum = evenSum;
res.oddSum = oddSum;
return res;
}
Hope this will help

Categories

Resources