Quantcast
Channel: All about basic binary - Code Golf Stack Exchange
Viewing all articles
Browse latest Browse all 23

Answer by plannapus for All about basic binary

$
0
0

R, 9483 79

n=scan();cat((2:n)[!sapply(2:n,function(x){while(n&n%%x<2)n=n%/%x;n})],sep="\n")

Usage:

> n=scan();cat((2:n)[!sapply(2:n,function(x){while(n&n%%x<2)n=n%/%x;n})],sep="\n")1: 820002: Read 1 item23458199982000> n=scan();cat((2:n)[!sapply(2:n,function(x){while(n&n%%x<2)n=n%/%x;n})],sep="\n")1: 12343212: Read 1 item2111112343201234321

The core of the function is !sapply(2:n,function(x){while(n&n%%x<2)n=n%/%x;n}) which, for each base x from 2 to n, keep the quotient n/x as long as the remainder is either 0 and 1. It then outputs the result (which is 0 if all remainders were either 1 or 0) and negates it (0 negates to TRUE, everything else negates to FALSE). Thanks to function scope, there is no need to make a dummy variable for n. The resulting vector of booleans is then used to index 2:n and therefore outputs only the bases for which it worked.


Viewing all articles
Browse latest Browse all 23

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>