Javascript factorial program - math

Why does this program not work?
This is an exercise from http://www.freecodecamp.com/challenges/bonfire-factorialize-a-number
function factorialize(num)
{
for (i=num; i>0; i--)
{
num*= num[i];
}
return num;
}
factorialize(5);

Just a bit too late...
You just should use num *= i; instead of num *= num[i]. What your code did is trying to access the property i of the number object num, which is undefined.
Also you should change your loop initialization to for(var i = num - 1; i > 1; i--) to just create a local variable and not a global one. Also, multiplying num by num (first loop cycle) would give incorrect results. And last but not least, multiplying by 1 (last loop cycle) is useless.

You multiply with num[i] but num isn't an array (that is where you get the error). Also, your first iteration would multiply 5*5 which is wrong, it should be 5*4, so we start at i=num-1. and also, i>1 is enough, the num *= 1is pretty pointless.
this works:
function factorialize(num)
{
for (i=num-1; i>1; i--)
{
num*= i;
}
return num;
}
factorialize(5);

#Feinmann can achieve this answer using below recursive function.
function factorialize(num) {
if(num==0) {
return 1;
}
return num * factorialize(num-1);
}

Related

How can I find a square root in simplest form given an integer? (Java)

I'm trying to compute the simplest form of the square root of an integer. My Java knowledge is rather limited, but I know many of the basics and such. I can't figure out how to find a simplest form square root given the input of a number to take the square root of.
Ex: User inputs 150, and I take the square root of that in simplest form (5√6).
Quick note: I haven't technically learned arrays and array lists yet so I can't use those for the code.
Simply divide out the all the perfect squares you can.
Ideally you would loop over the primes using a precomputed table of primes. The left over number is the portion that is not a perfect square:
int num = 2*3*3*5*7*7*7*7*11; // 9; // 16; // 150; // input
int root = 1;
for (int d = 2; d*d <= num; )
if ((num % (d*d)) == 0) { // d^2 divides num
root *= d;
num /= d*d;
} else {
d++;
}
System.out.println( root + " * sqrt(" + num + ")");
Edited: Thanks to Mark Dickenson's comments.

Exception in thread "main" java.lang.StackOverflowError at Solution.recur(File.java:58)

class Solution{
ArrayList subsetSums(ArrayList arr, int N){
int sum=0;
ArrayList<Integer> temparr = new ArrayList<>();
for(int i=1;i<=arr.size();i++)
{
for(int j = 0; i < arr.size()-i+1 ; j++)
temparr.add(recur(arr,i,j,sum));
}
return temparr;
}
int recur(ArrayList<Integer> arr,int i,int j,int sum)
{
int index = j;
int len = i;
int Sum = sum;
if(len==0)
{
return Sum;
}
Sum += arr.get(index);
return recur(arr,len--,index++,Sum);
}
}
,,,
I'm getting stack overflow error in 'return recur(arr,len--,index++,Sum);'
'''
I think, the main problem here (see comments for potential other problems) is the way you are trying to pass changed arguments to the recursive invocation:
recur(arr,len--,index++,Sum)
Actually this will call recur with the unchanged values of len and index because the operators ++ and -- (when written on the right side of a variable) are defined to return the original value of the variable and then update the variable's value.
Use (I would prefer this)
recur(arr, len-1, index+1, Sum)
or (okay, but the assignment is not needed)
recur(arr, --len, ++index, Sum)
to actually pass the modified value to the function.
Java has a recursion limit. The way to fix this is replace the recursion with a loop. (Or change the function so it does not recur as much. Infinite loops are a problem just as infinite recursion is).
A few tips for the future:
Google the documentation for errors
State the language with a tag in posts
Don't use formatting of line 1
Debug with print statements

Program returns 0 but only to "one up" in recursion, but I want it to go to the "very top"? Is this possible?

I'm new to using recursion and I'm trying to get my palindrome program to work. This is what I am trying to do: if a character is not equal, I return 0. If not, I keep recursing while increasing the i and decreasing the j. If the i is no longer less than the j, i want to say that the recursion is done, so I want to return that the word is a palindrome (=1).
But when I input a word that is not a palindrome, I correctly return a 0. (I can see this when I debug). But-- then at the end, it also returns a 1. I assume this has something to do with the fact that recursion means that the program keeps going, and the 0 gets returned to something I had previously been doing before. But- I want the 0 to go to the very top.
Is there some way around this problem? Or am I doing something wrong? Sorry if this is really basic.
Thanks in advance. Here is my code:
public static int checkIfPalindrome(String s, int i, int j) {
if (i<j) {
if (s.charAt(i) == s.charAt(j)) {
checkIfPalindrome(s, i+1, j-1);
}
else {
return 0;
}
}
return 1;
}
Once you know your pointers haven't collided, and the characters they point to are the same, then the return value of this method is the return value of the recursive call. I've fixed your code to do this below but I have also reorganized it a different way, as there are other ways to go about the problem:
public static int checkIfPalindrome(String s, int i, int j) {
if (i >= j) {
return 1;
}
if (s.charAt(i) != s.charAt(j)) {
return 0;
}
return checkIfPalindrome(s, i + 1, j - 1);
}

Appending to / removing elements from vector while iterating over said vector [duplicate]

What is the idiomatic way to iterate (read) over the first half of the vector and change the structure of the second half of the vector depending on the first? This is very abstract but some algorithms could be boiled down to this problem. I want to write this simplified C++ example in Rust:
for (var i = 0; i < vec.length; i++) {
for (var j = i + 1 ; j < vec.length; j++) {
if (f(vec[i], vec[j])) {
vec.splice(j, 1);
j--;
}
}
}
An idiomatic solution of this generic problem will be the same for Rust and C, as there's no constraints which would allow simplification.
We need to use indexes because vector reallocation will invalidate the references contained by the iterators. We need to compare the index against the current length of the vector on each cycle because the length could be changed. Thus an idiomatic solution will look like this:
let mut i = 0;
while i < v.len() {
let mut j = i + 1;
while j < v.len() {
if f(v[i], v[j]) {
v.splice(j, 1);
} else {
j += 1;
}
}
i += 1;
}
Playground link
While this code covers the general case, it is rarely useful. It doesn't capture specifics, which are usually inherent to the problem at hand. In turn, the compiler is unable to catch any errors at compile time. I don't advise writing something like this without considering another approaches first.

Compile-time generated 2D array in D

In my program I need to generate array with powers' (from 0 to 5) sum of numbers from 1 to 100,000.
So I tried to compile this code:
const enum size_t MAX_ARRAY_SIZE = 100_000 + 1;
const enum size_t MAX_POWER_SIZE = 5 + 1;
const enum power_sum = calc_power_sum();
// some unimportant code here
pure ulong[MAX_POWER_SIZE][MAX_ARRAY_SIZE] calc_power_sum() {
ulong[MAX_POWER_SIZE][MAX_ARRAY_SIZE] power_sum;
power_sum[0][] = 1;
foreach (x, ref element; power_sum[1]) {
element = x;
}
foreach (n; 2 .. MAX_POWER_SIZE) {
foreach (x, ref element; power_sum[n]) {
element = power_sum[n - 1][x] * power_sum[1][x];
}
}
foreach (ref power; power_sum) {
foreach (x; 1 .. MAX_ARRAY_SIZE) {
power[x] += power[x - 1]; // error appears here
}
}
return power_sum;
}
But compiler says:
$ dmd problem.d
problem.d(130): Error: array index 6 is out of bounds [1LU, 2LU, 3LU, 4LU, 5LU, 6LU][0 .. 6]
problem.d(15): called from here: calc_power_sum()
What am I doing wrong?
At first glance looks like you have simply misunderstood array dimension order. You have
ulong[MAX_POWER_SIZE][MAX_ARRAY_SIZE]
and your code assumes directly opposite
ulong[MAX_ARRAY_SIZE][MAX_POWER_SIZE]
Also I am afraid 100 000 may be a bit too much, after above mentioned fix I get an internal compiler error. Works for smaller MAX_ARRAY_SIZE values though.
As Mihail said, you should reverse the order of dimensions.
However, you most likely won't be able to do what you plan for all sizes because the maximum size of static array is limited in D ( http://dlang.org/arrays.html ) :
The total size of a static array cannot exceed 16Mb.

Resources