Some Basic Programs
R-program to check if a Number is Odd or Even:
R-Code:
#Function define for checking Odd_Even for a given number
Odd_Even_Check<-function(N)
{
if (N%%2== 0)
{
print("Number is even")
}
else
{
print("Number is odd")
}
}
Odd_Even_Check(20)
Output:
> Odd_Even_Check(20)
[1] "Number is even"
Calculate the Sum of Fisrt n Natural Number Using R:
R-Code:
#Function define for Sum of N natural numbers using R
N_Sum=function(N)
{
if(N<=0)
{
print("Please Enter the positive integer.")
}
else
{
Sum=0
if(N>0)
{
for (i in 1:N)
{
Sum=Sum+i
}
print(Sum)
}
}
}
N_Sum(10)
N_Sum(100)
N_Sum(-1)
Output:
> N_Sum(10)
[1] 55
> N_Sum(100)
[1] 5050
> N_Sum(-1)
[1] "Please Enter the positive integer."
R-Code:
#Program to Print Prime Numbers From 1 to N in C
Prime_Numbers <- function(n)
{
if (n >= 2)
{
x = seq(2, n)
prime_nums = c()
for (i in seq(2, n))
{
if (any(x == i))
{
prime_nums = c(prime_nums, i)
x = c(x[(x %% i) != 0], i)
}
}
return(prime_nums)
}
else
{
stop("Input number should be at least 2.")
}
}
Prime_Numbers(25)
Output:
> Prime_Numbers(25)
[1] 2 3 5 7 11 13 17 19 23
Find the Factorial n Using R-Programming:
R-Code:
#Find the Factorial n using R.
Fact<-function(n)
{
Prod<-1
for (i in 1:n) {
Prod=Prod*i
}
return(Prod)
}
Fact(5)
Fact(6)
Fact(7)
Output:
> Fact(5)
[1] 120
> Fact(6)
[1] 720
> Fact(7)
[1] 5040
Checking Prime Number from list of a numbers Using R:
R-Code:
Find_Prime_No <- function(n) {
if (n == 2) {
return(TRUE)
}
if (n <= 1) {
return(FALSE)
}
for (i in 2:(n-1)) {
if (n %% i == 0) {
return(FALSE)
}
}
return(TRUE)
}
X<-list(12,45,67,23,89,13,29)
Checking<-sapply(X,Find_Prime_No)
Checking
Output:
> Checking
[1] FALSE FALSE TRUE TRUE TRUE TRUE TRUE
Find the G.C.D or H.C.F and L.C.M Using R:
R-Code:
GCD <- function(a, b) {
while (b != 0) {
remainder <- a %% b
a <- b
b <- remainder
}
return(a)
}
LCM<-function(a,b){
l=(a*b)/GCD(a,b)
return(l)
}
GCD(12,45)
LCM(12,45)
Output:
> GCD(12,45)
[1] 3
> LCM(12,45)
[1] 180
Create Power Function Using R:
R-Code:
Pow_N<-function(x,n){
return(x^n)
}
Pow_N(10,4)
Pow_N(9,3)
Output:
> Pow_N(10,4)
[1] 10000
> Pow_N(9,3)
[1] 729
Permutation and Combination Using R:
R-Code:
N_P_R<-function(n,r){
if(n<r){
print("Enter Positive integer n greater than r.")
}else{
npr<-factorial(n)/factorial(n-r)
}
return(npr)
}
N_C_R<-function(n,r){
return(1/factorial(r)*N_P_R(n,r))
}
N_P_R(4,3)
N_C_R(7,5)
Output:
> N_P_R(4,3)
[1] 24
> N_C_R(7,5)
[1] 21
Sum of Square and sum of cube of First n Natural numbers Using R:
R-Code:
#Find the Factorial n using R.
Sum_Square<-function(n){
sum<-0
if(n<=0){
print("Enter Positive integer. ")
}else{
sum<-sum+(n/6)*(n+1)*(2*n+1)
}
return(sum)
}
Sum_Cube<-function(n){
sum<-0
if(n<=0){
print("Enter Positive integer. ")
}else{
sum=sum+(n*(n+1)/2)^2
}
return(sum)
}
Sum_Square(5)
Sum_Cube(5)
Output:
> Sum_Square(5)
[1] 55
> Sum_Cube(5)
[1] 225
Sum of Square from a List of integers:
R-Code:
My_list<-list(c(13,24,9,34))
Add<-sapply(My_list, sum)
Add
Output:
> Add
[1] 80