Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
29
Task/Happy-numbers/R/happy-numbers-1.r
Normal file
29
Task/Happy-numbers/R/happy-numbers-1.r
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
is.happy <- function(n)
|
||||
{
|
||||
stopifnot(is.numeric(n) && length(n)==1)
|
||||
getdigits <- function(n)
|
||||
{
|
||||
as.integer(unlist(strsplit(as.character(n), "")))
|
||||
}
|
||||
digits <- getdigits(n)
|
||||
previous <- c()
|
||||
repeat
|
||||
{
|
||||
sumsq <- sum(digits^2, na.rm=TRUE)
|
||||
if(sumsq==1L)
|
||||
{
|
||||
happy <- TRUE
|
||||
break
|
||||
} else if(sumsq %in% previous)
|
||||
{
|
||||
happy <- FALSE
|
||||
attr(happy, "cycle") <- previous
|
||||
break
|
||||
} else
|
||||
{
|
||||
previous <- c(previous, sumsq)
|
||||
digits <- getdigits(sumsq)
|
||||
}
|
||||
}
|
||||
happy
|
||||
}
|
||||
1
Task/Happy-numbers/R/happy-numbers-2.r
Normal file
1
Task/Happy-numbers/R/happy-numbers-2.r
Normal file
|
|
@ -0,0 +1 @@
|
|||
is.happy(2)
|
||||
2
Task/Happy-numbers/R/happy-numbers-3.r
Normal file
2
Task/Happy-numbers/R/happy-numbers-3.r
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
#Find happy numbers between 1 and 50
|
||||
which(apply(rbind(1:50), 2, is.happy))
|
||||
9
Task/Happy-numbers/R/happy-numbers-4.r
Normal file
9
Task/Happy-numbers/R/happy-numbers-4.r
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
#Find the first 8 happy numbers
|
||||
happies <- c()
|
||||
i <- 1L
|
||||
while(length(happies) < 8L)
|
||||
{
|
||||
if(is.happy(i)) happies <- c(happies, i)
|
||||
i <- i + 1L
|
||||
}
|
||||
happies
|
||||
Loading…
Add table
Add a link
Reference in a new issue