Want to get involved? We're always looking for ideas and content for Weekly Challenges.
SUBMIT YOUR IDEAView last week's challenge HERE.
This week's challenge is simple to grasp, but more difficult to execute. This week, let's make an application that finds the closest prime number to a users input.
A prime number is a number that has two positive divisors - 1 and itself.
Without the use of a lookup table, please build an app that takes a user-entered number and returns the closest prime number to the entered number.
Fun fact: this post went live on 07/31/2017 - a very prime day indeed!
I hope that I didn't make my life harder with this prime problem. I created an application that on output answers your question, plus it states:
Is the number itself PRIME?
What is the previous largest PRIME number?
What is the next largest PRIME number?
On input I permit values up to 10,000.
Cheers,
Mark
Can we use R?
# Expectes a field named "Number" # Adds the fields "Prev_Prime" and "Next_Prime" # Function to check if a number is prime is.prime <- function(n){ n == 2L || all(n %% 2L:max(2,floor(sqrt(n))) != 0)} # Function to get next prime next.prime <- function(n){ while(! is.prime(n)){n<-n+1} return(n)} # Function to get previous prime prev.prime <- function(n){ while(! is.prime(n)){n<-n-1} return(n)} # Read the Table in the_data<-read.Alteryx("#1", mode="data.frame") # Compute the previous prime number the_data<-cbind(the_data,Prev_Prime = mapply(function(n) prev.prime(n),the_data$Number)) # Compute the next prime number the_data<-cbind(the_data,Next_Prime = mapply(function(n) next.prime(n),the_data$Number)) # Output the data write.Alteryx(the_data, 1)
IF [Number]-[Prev_Prime]<[Next_Prime]-[Number] THEN [Prev_Prime] ELSE [Next_Prime] ENDIF
My solution attached! Definitely borrowed the concept of testing for closest prime in either direction from @MarqueeCrew (thanks Mark!), but definitely a different path to the final solution. Added one more calculation for which number was technically "closer": Number itself, the next prime, the previous prime, or tied.
Happy Day o' Prime Numbers!
NJ
Here my Solution!!!
Into this app you can write your number and it finds the nearest prime number (above or below the chosen number).
1. Check if number is prime (by checking the number doesn't divide cleanly by any number from 2 up to the square root of the number)
2. If not prime -> check number +/- 1, then +/- 2, then +/- 3, etc. Do this by using an iterative macro and using number = number * (-1)^n x n where n is the number of iterations.
Ah lovely @JoeM! Spent the last week playing with iterative macros so seemed like an obvious choice when I saw the challenge. Solution below:
Thoroughly enjoyable.
Luke
Alteryx Certified Partner with Keyrus UK