-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathGoldbach_conjecture.R
More file actions
104 lines (84 loc) · 2.24 KB
/
Goldbach_conjecture.R
File metadata and controls
104 lines (84 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
##########################################
#
#
# Goldbach's Conjecture
# Two primes for a given sum (even int)
#
# Series:
# Little Useless-useful R functions #52
# Created: Jul 15, 2023
# Author: Tomaz Kastrun
# Blog: tomaztsql.wordpress.com
# V.1.0
#
# Changelog:
#
##########################################
# sieve of sundaram
sieve_of_sundaram <- function(limit) {
n <- (limit - 1) %/% 2
sieve <- rep(TRUE, n + 1)
for (i in 1:n) {
j <- 1
while (i+j+2*i*j <= n) {
sieve[i+j+2*i*j] <- FALSE
j <- j + 1
}
}
primes <- c(2,(2*(1:n)+1)[sieve])
return(primes)
}
#list of all primes until "limit"
#sieve_of_sundaram(limit)
# is prime
is_prime <- function(n) {
if (n <= 1) return(FALSE)
if (n <= 3) return(TRUE)
if (n %% 2 == 0 || n %% 3 == 0) return(FALSE)
i <- 5
while (i*i <= n) {
if (n %% i == 0 || n %% (i + 2) == 0) return(FALSE)
i <- i + 6
}
return(TRUE)
}
## goldbach for even numbers
goldbach_conjecture <- function(even_num) {
if (even_num <= 2 || even_num %% 2 != 0) {
return("Number must be even and greater than 2.")
}
c <- NULL
for (i in 2:(even_num / 2)) {
if (is_prime(i) && is_prime(even_num - i)) {
#cat("Goldbach's pairs for", even_num, "are:", i, "+", even_num - i, "\n")
c <- cbind(c,i) # nof solutions
}
}
#return(length(c))
return(c)
}
# test
goldbach_conjecture(870)
#make some 1000 solutions
sol <- NULL
for (i in seq(4,1000, by=2)){
nof_solutions <- goldbach_conjecture(i)
sol <- rbind(sol, data.frame(n=i, nof=nof_solutions))
}
# plot solutions; alternating solutions
plot(sol$n, sol$nof, type = "p", xlab = "Even number", ylab = "Number of Solutions", main = "Goldbach's Conjecture")
reg<-lm(nof ~ n, data = sol)
abline(reg, col="red")
# most frequent primes:
fre <- NULL
for (i in seq(4,1000, by=2)){
sols <- goldbach_conjecture(i)
fre <- cbind(fre, sols)
}
# prepare solutions
solutions_freq<- data.frame(table(t(fre)))
# visualisation
solutions_freq <- solutions_freq[which(as.integer(solutions_freq$Freq) > 1),]
plot(x=solutions_freq$Var1, y=solutions_freq$Freq,
xlab = "Prime number", ylab = "Frequency of prime in sum", main = "Frequencies of prime numbers for
Goldbach's Conjecture for first \n 1000 even integers.")