factors
Algorithm to find all the exact divisors of a given integer
First, your code should have the condition of i <= n/2, otherwise it can miss one of the factors, for example 6 will not be printed if n=12. Run the loop to the square root of the number (ie. i <= sqrt(n)) and print both i and n/i (both will be multiples of n). { … Read more
Find the most frequent value by row
Something like : apply(df,1,function(x) names(which.max(table(x)))) [1] “red” “yellow” “green” In case there is a tie, which.max takes the first max value. From the which.max help page : Determines the location, i.e., index of the (first) minimum or maximum of a numeric vector. Ex : var4 <- c(“yellow”,”green”,”yellow”) df <- data.frame(cbind(id, var1, var2, var3, var4)) > … Read more
Why is the terminology of labels and levels in factors so weird?
I think the way to think about the difference between labels and levels (ignoring the labels() function that Tommy describes in his answer) is that levels is intended to tell R which values to look for in the input (x) and what order to use in the levels of the resulting factor object, and labels … Read more
nᵗʰ ugly number
A simple fast solution in Java. Uses approach described by Anon.. Here TreeSet is just a container capable of returning smallest element in it. (No duplicates stored.) int n = 20; SortedSet<Long> next = new TreeSet<Long>(); next.add((long) 1); long cur = 0; for (int i = 0; i < n; ++i) { cur = next.first(); … Read more
Enumerate factors of a number directly in ascending order without sorting?
This answer gives a C implementation that I believe is the fastest and most memory-efficient. Overview of algorithm. This algorithm is based on the bottom-up merge approach introduced by Will Ness in another answer, but is further simplified so that the lists being merged do not actually ever exist anywhere in memory. The head element … Read more
Finding largest prime number out of 600851475143?
Not only does your prime checking function always return false; even if it were functioning properly, your main loop does not seek the input number’s factors at all, but rather just the largest prime smaller or equal to it. In pseudocode, your code is equivalent to: foo(n): x := 0 ; foreach d from 1 … Read more
Segmented Sieve of Eratosthenes?
The basic idea of a segmented sieve is to choose the sieving primes less than the square root of n, choose a reasonably large segment size that nevertheless fits in memory, and then sieve each of the segments in turn, starting with the smallest. At the first segment, the smallest multiple of each sieving prime … Read more