Prime generator program SPOJ wrong answer - algorithm

Problem Statement
Input
The input begins with the number t of test cases in a single line
(t<=10). In each of the next t lines there are two numbers m and n (1
<= m <= n <= 1000000000, n-m<=100000) separated by a space.
Output
For every test case print all prime numbers p such that m <= p <= n,
one number per line, test cases separated by an empty line.
Example
Input:
2
1 10
3 5
Output:
2
3
5
7
3
5
My Problem
I have tried to write this problem with golang, at beginning I got time limit exceed error, then I solved it with finding the biggest n and only generate prime once. But now I got wrong answer error. Anyone can help to to find the bug? I can't figure it out. Thanks.
package main
import (
"fmt"
"math"
)
func main() {
var k, j, i, max_m, max_n, test_cases, kase int64
fmt.Scanln(&test_cases)
case_m, case_n := make([]int64, test_cases), make([]int64, test_cases)
EratosthenesArray := make(map[int64][]bool)
max_m = 0
max_n = 0
for i = 0; i < test_cases; i++ {
fmt.Scanf("%d %d", &case_m[i], &case_n[i])
if case_m[i] > case_n[i] {
case_m[i] = 0
case_n[i] = 0
}
if max_m < case_m[i] {
max_m = case_m[i]
}
if max_n < case_n[i] {
max_n = case_n[i]
}
length := case_n[i] - case_m[i] + 1
EratosthenesArray[i] = make([]bool, length)
}
if max_m <= max_n {
upperbound := int64(math.Sqrt(float64(max_n)))
UpperboundArray := make([]bool, upperbound+1)
for i = 2; i <= upperbound; i++ {
if !UpperboundArray[i] {
for k = i * i; k <= upperbound; k += i {
UpperboundArray[k] = true
}
for kase = 0; kase < test_cases; kase++ {
start := (case_m[kase] - i*i) / i
if case_m[kase]-i*i < 0 {
start = i
}
for k = start * i; k <= case_n[kase]; k += i {
if k >= case_m[kase] && k <= case_n[kase] {
EratosthenesArray[kase][k-case_m[kase]] = true
}
}
}
}
}
}
for i = 0; i < test_cases; i++ {
k = 0
for j = 0; j < case_n[i]-case_m[i]; j++ {
if !EratosthenesArray[i][j] {
ret := case_m[i] + j
if ret > 1 {
fmt.Println(ret)
}
}
}
fmt.Println()
}
}

according to the comments, the output for each prime number range is always have one line short, so here is the ACCEPTED solution
package main
import (
"fmt"
"math"
)
func main() {
var k, j, i, max_m, max_n, test_cases, kase int64
fmt.Scanln(&test_cases)
case_m, case_n := make([]int64, test_cases), make([]int64, test_cases)
EratosthenesArray := make(map[int64][]bool)
max_m = 0
max_n = 0
for i = 0; i < test_cases; i++ {
fmt.Scanf("%d %d", &case_m[i], &case_n[i])
if case_m[i] > case_n[i] {
case_m[i] = 0
case_n[i] = 0
}
if max_m < case_m[i] {
max_m = case_m[i]
}
if max_n < case_n[i] {
max_n = case_n[i]
}
length := case_n[i] - case_m[i] + 1
EratosthenesArray[i] = make([]bool, length)
}
if max_m <= max_n {
upperbound := int64(math.Sqrt(float64(max_n)))
UpperboundArray := make([]bool, upperbound+1)
for i = 2; i <= upperbound; i++ {
if !UpperboundArray[i] {
for k = i * i; k <= upperbound; k += i {
UpperboundArray[k] = true
}
for kase = 0; kase < test_cases; kase++ {
start := (case_m[kase] - i*i) / i
if case_m[kase]-i*i < 0 {
start = i
}
for k = start * i; k <= case_n[kase]; k += i {
if k >= case_m[kase] && k <= case_n[kase] {
EratosthenesArray[kase][k-case_m[kase]] = true
}
}
}
}
}
}
for i = 0; i < test_cases; i++ {
k = 0
for j = 0; j <= case_n[i]-case_m[i]; j++ {
if !EratosthenesArray[i][j] {
ret := case_m[i] + j
if ret > 1 {
fmt.Println(ret)
}
}
}
fmt.Println()
}
}
Note that I only changed one line from for j = 0; j < case_n[i]-case_m[i]; j++ { to for j = 0; j <= case_n[i]-case_m[i]; j++ {
And the execution time is about 1.08s, memory is about 772M (but seems the initial memory for golang in spoj is 771M, so it might be about 1M memory usage)

Related

How to completly making Newton-Raphson Method in golang?

package main
import (
"pars"
"fmt"
)
func Newton(x_first, ddd float64, L []pars.Querry) float64 {
var x_1, x_2, result float64
x_2 = x_first + ddd
f_2 = pars.Function(x_2, L)
f_1 = (f_2 - pars.Function(gox_first)) / ddd
x_2 = x_first - f_2/f_1
return (x_2)
}
func main() {
var x_1, epsilon, Delta, result, check float64
var Max_iteration int
var i, j, k int
epsilon = 0.001
Delta = 0.001
Max_iteration = 100
Equation := pars.ReadFuction()
LIST := pars.Make_list(Equation)
LIST := pars.Insert(LIST)
x_1 = 0.0
for i := 0; i < Max_iteration; i++ {
result = New(funcs, x_1, Delta)
check = result - x_1
if check < 0.0 {
check = -check
}
if check < epsilon {
for k = 0; k <= j; k++ {
if x[k-1] < (result+epsilon) && x[k-1] > (result-epsilon) {
printf(" --> No more ROOT!!\n")
exit(0)
}
prinft("The %3d th ROOT is %10.3f\n", j+1, result)
x[j] = result
j++
x_1 = result + pow(-1, j)*10.0
}
} else
{x_1 = result}
}
}
}

generate combinations/permutation of specific length

The project is more complex but the blocking issue is: How to generate a sequence of words of specific length from a list?
I've found how to generate all the possible combinations(see below) but the issue is that I need only the combinations of specific length.
Wolfram working example (it uses permutations though, I need only combinations(order doesn't matter)) :
Permutations[{a, b, c, d}, {3}]
Example(pseudo go):
list := []string{"alice", "moon", "walks", "mars", "sings", "guitar", "bravo"}
var premutationOf3
premutationOf3 = premuate(list, 3)
// this should return a list of all premutations such
// [][]string{[]string{"alice", "walks", "moon"}, []string{"alice", "signs", "guitar"} ....}
Current code to premutate all the possible sequences (no length limit)
for _, perm := range permutations(list) {
fmt.Printf("%q\n", perm)
}
func permutations(arr []string) [][]string {
var helper func([]string, int)
res := [][]string{}
helper = func(arr []string, n int) {
if n == 1 {
tmp := make([]string, len(arr))
copy(tmp, arr)
res = append(res, tmp)
} else {
for i := 0; i < n; i++ {
helper(arr, n-1)
if n%2 == 1 {
tmp := arr[i]
arr[i] = arr[n-1]
arr[n-1] = tmp
} else {
tmp := arr[0]
arr[0] = arr[n-1]
arr[n-1] = tmp
}
}
}
}
helper(arr, len(arr))
return res
}
I implement twiddle algorithm for generating combination in Go. Here is my implementation:
package twiddle
// Twiddle type contains all information twiddle algorithm
// need between each iteration.
type Twiddle struct {
p []int
b []bool
end bool
}
// New creates new twiddle algorithm instance
func New(m int, n int) *Twiddle {
p := make([]int, n+2)
b := make([]bool, n)
// initiate p
p[0] = n + 1
var i int
for i = 1; i != n-m+1; i++ {
p[i] = 0
}
for i != n+1 {
p[i] = i + m - n
i++
}
p[n+1] = -2
if m == 0 {
p[1] = 1
}
// initiate b
for i = 0; i != n-m; i++ {
b[i] = false
}
for i != n {
b[i] = true
i++
}
return &Twiddle{
p: p,
b: b,
}
}
// Next creates next combination and return it.
// it returns nil on end of combinations
func (t *Twiddle) Next() []bool {
if t.end {
return nil
}
r := make([]bool, len(t.b))
for i := 0; i < len(t.b); i++ {
r[i] = t.b[i]
}
x, y, end := t.twiddle()
t.b[x] = true
t.b[y] = false
t.end = end
return r
}
func (t *Twiddle) twiddle() (int, int, bool) {
var i, j, k int
var x, y int
j = 1
for t.p[j] <= 0 {
j++
}
if t.p[j-1] == 0 {
for i = j - 1; i != 1; i-- {
t.p[i] = -1
}
t.p[j] = 0
x = 0
t.p[1] = 1
y = j - 1
} else {
if j > 1 {
t.p[j-1] = 0
}
j++
for t.p[j] > 0 {
j++
}
k = j - 1
i = j
for t.p[i] == 0 {
t.p[i] = -1
i++
}
if t.p[i] == -1 {
t.p[i] = t.p[k]
x = i - 1
y = k - 1
t.p[k] = -1
} else {
if i == t.p[0] {
return x, y, true
}
t.p[j] = t.p[i]
t.p[i] = 0
x = j - 1
y = i - 1
}
}
return x, y, false
}
you can use my tweedle package as follow:
tw := tweedle.New(1, 2)
for b := tw.Next(); b != nil; b = tw.Next() {
fmt.Println(b)
}

How to solve Spiral Matrix in go

https://leetcode.com/problems/spiral-matrix/
golang implement.
the result as follow:
Run Code Status: Runtime Error
Run Code Result: ×
Your input
[]
Your answer
Expected answer
[]
Show Diff
why [] is the test case ,it's just a one-dimensional slice ?
my code is :
func sprial(begin_r, begin_c, row, col int, matrix [][]int) []int {
s := make([]int, col*row, col*row+10)
k := 0
if row == 1 && col == 1 {
s[k] = matrix[begin_r][begin_c]
return s
} else if row == 1 {
return matrix[begin_r][begin_c : col-1]
} else if col == 1 {
return matrix[begin_r : row-1][begin_c]
} else {
for i := begin_c; i < col; i++ {
s[k] = matrix[begin_r][i]
k++
}
for i := begin_r + 1; i < row; i++ {
s[k] = matrix[i][col-1]
k++
}
for i := col - 2; i >= begin_c; i-- {
s[k] = matrix[row-1][i]
k++
}
for i := row - 2; i >= begin_r+1; i-- {
s[k] = matrix[i][begin_c]
k++
}
return s[:k-1]
}
}
func spiralOrder(matrix [][]int) []int {
m := len(matrix)
n := len(matrix[0])
i := 0
j := 0
// var rS []int
k := 0
//s1 := make([]int, m*n, m*n)
var s1 = []int{}
for {
if m <= 0 || n <= 0 {
break
}
s := sprial(i, j, m, n, matrix)
if k == 0 {
s1 = s
} else {
s1 = append(s1, s...)
}
i++
j++
m -= 2
n -= 2
k++
}
return s1
}
func spiralOrder(matrix [][]int) []int {
if len(matrix) == 0 || len(matrix[0]) == 0 {
return nil
}
m, n := len(matrix), len(matrix[0])
next := nextFunc(m, n)
res := make([]int, m*n)
for i := range res {
x, y := next()
res[i] = matrix[x][y]
}
return res
}
func nextFunc(m, n int) func() (int, int) {
top, down := 0, m-1
left, right := 0, n-1
x, y := 0, -1
dx, dy := 0, 1
return func() (int, int) {
x += dx
y += dy
switch {
case y+dy > right:
top++
dx, dy = 1, 0
case x+dx > down:
right--
dx, dy = 0, -1
case y+dy < left:
down--
dx, dy = -1, 0
case x+dx < top:
left++
dx, dy = 0, 1
}
return x, y
}
}
Source: https://github.com/aQuaYi/LeetCode-in-Go/blob/master/Algorithms/0054.spiral-matrix/spiral-matrix.go
This repository has most of the solutions to LeetCode problems in a very optimal manner. Please do take a look. Hope it helps.

Generating prime numbers in Go

EDIT: The question essentially asks to generate prime numbers up to a certain limit. The original question follows.
I want my if statement to become true if only these two conditions are met:
for i := 2; i <= 10; i++ {
if i%i == 0 && i%1 == 0 {
} else {
}
}
In this case every possible number gets past these conditions, however I want only the numbers 2, 3, 5, 7, 11... basically numbers that are divisible only with themselves and by 1 to get past, with the exception being the very first '2'. How can I do this?
Thanks
It seems you are looking for prime numbers. However the conditions you described are not sufficient. In fact you have to use an algorithm to generate them (up to a certain limit most probably).
This is an implementation of the Sieve of Atkin which is an optimized variation of the ancient Sieve of Eratosthenes.
Demo: http://play.golang.org/p/XXiTIpRBAu
For the sake of completeness:
package main
import (
"fmt"
"math"
)
// Only primes less than or equal to N will be generated
const N = 100
func main() {
var x, y, n int
nsqrt := math.Sqrt(N)
is_prime := [N]bool{}
for x = 1; float64(x) <= nsqrt; x++ {
for y = 1; float64(y) <= nsqrt; y++ {
n = 4*(x*x) + y*y
if n <= N && (n%12 == 1 || n%12 == 5) {
is_prime[n] = !is_prime[n]
}
n = 3*(x*x) + y*y
if n <= N && n%12 == 7 {
is_prime[n] = !is_prime[n]
}
n = 3*(x*x) - y*y
if x > y && n <= N && n%12 == 11 {
is_prime[n] = !is_prime[n]
}
}
}
for n = 5; float64(n) <= nsqrt; n++ {
if is_prime[n] {
for y = n * n; y < N; y += n * n {
is_prime[y] = false
}
}
}
is_prime[2] = true
is_prime[3] = true
primes := make([]int, 0, 1270606)
for x = 0; x < len(is_prime)-1; x++ {
if is_prime[x] {
primes = append(primes, x)
}
}
// primes is now a slice that contains all primes numbers up to N
// so let's print them
for _, x := range primes {
fmt.Println(x)
}
}
Here's a golang sieve of Eratosthenes
package main
import "fmt"
// return list of primes less than N
func sieveOfEratosthenes(N int) (primes []int) {
b := make([]bool, N)
for i := 2; i < N; i++ {
if b[i] == true { continue }
primes = append(primes, i)
for k := i * i; k < N; k += i {
b[k] = true
}
}
return
}
func main() {
primes := sieveOfEratosthenes(100)
for _, p := range primes {
fmt.Println(p)
}
}
The simplest method to get "numbers that are divisible only with themselves and by 1", which are also known as prime numbers is: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
It's not a "simple if statement".
If you don't mind a very small chance (9.1e-13 in this case) of them not being primes you can use ProbablyPrime from math/big like this (play)
import (
"fmt"
"math/big"
)
func main() {
for i := 2; i < 1000; i++ {
if big.NewInt(int64(i)).ProbablyPrime(20) {
fmt.Printf("%d is probably prime\n", i)
} else {
fmt.Printf("%d is definitely not prime\n", i)
}
}
}
Just change the constant 20 to be as sure as you like that they are primes.
Simple way(fixed):
package main
import "math"
const n = 100
func main() {
print(1, " ", 2)
L: for i := 3; i <= n; i += 2 {
m := int(math.Floor(math.Sqrt(float64(i))))
for j := 2; j <= m; j++ {
if i%j == 0 {
continue L
}
}
print(" ", i)
}
}
just change the 100 in the outer for loop to the limit of the prime number you want to find. cheers!!
for i:=2; i<=100; i++{
isPrime:=true
for j:=2; j<i; j++{
if i % j == 0 {
isPrime = false
}
}
if isPrime == true {
fmt.Println(i)
}
}
}
Here try this by checking all corner cases and optimised way to find you numbers and run the logic when the function returns true.
package main
import (
"math"
"time"
"fmt"
)
func prime(n int) bool {
if n < 1 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 && n > 2 {
return false
}
var maxDivisor = int(math.Floor(math.Sqrt(float64 (n))))
//d := 3
for d:=3 ;d <= 1 + maxDivisor; d += 2 {
if n%d == 0 {
return false
}
}
return true
}
//======Test Function=====
func main() {
// var t0 = time.Time{}
var t0= time.Second
for i := 1; i <= 1000; i++ {
fmt.Println(prime(i))
}
var t1= time.Second
println(t1 - t0)
}
package main
import (
"fmt"
)
func main() {
//runtime.GOMAXPROCS(4)
ch := make(chan int)
go generate(ch)
for {
prime := <-ch
fmt.Println(prime)
ch1 := make(chan int)
go filter(ch, ch1, prime)
ch = ch1
}
}
func generate(ch chan int) {
for i := 2; ; i++ {
ch <- i
}
}
func filter(in, out chan int, prime int) {
for {
i := <-in
if i%prime != 0 {
out <- i
}
}
}
A C like logic (old school),
package main
import "fmt"
func main() {
var num = 1000
for j := 2; j < num ; j++ {
var flag = 0
for i := 2; i <= j/2 ; i++ {
if j % i == 0 {
flag = 1
break
}
}
if flag == 0 {
fmt.Println(j)
}
}
}
Simple solution for generating prime numbers up to a certain limit:
func findNthPrime(number int) int {
if number < 1{
fmt.Println("Please provide positive number")
return number
}
var primeCounter, nthPrimeNumber int
for i:=2; primeCounter < number; i++{
isPrime := true
for j:=2; j <= int(math.Sqrt(float64(i))) && i != 2 ; j++{
if i % j == 0{
isPrime = false
}
}
if isPrime{
primeCounter++
nthPrimeNumber = i
fmt.Println(primeCounter, "th prime number is ", nthPrimeNumber)
}
}
fmt.Println("Nth prime number is ", nthPrimeNumber)
return nthPrimeNumber
}
A prime number is a positive integer that is divisible only by 1 and itself. For example: 2, 3, 5, 7, 11, 13, 17.
What is Prime Number?
A Prime Number is a whole number that cannot be made by multiplying other whole numbers
A prime number (or a prime) is a natural number greater than 1 that is not a product of two smaller natural numbers. A natural number greater than 1 that is not prime is called a composite number.
Go Language Program to Check Whether a Number is Prime or Not
https://www.golanguagehub.com/2021/01/primenumber.html

Go : longest common subsequence to print result array

I have implemented Longest Common Subsequence algorithm and getting the right answer for longest but cannot figure out the way to print out what makes up the longest common subsequence.
That is, I succeeded to get the length of longest commond subsequence array but I want to print out the longest subsequence.
The Playground for this code is here
http://play.golang.org/p/0sKb_OARnf
/*
X = BDCABA
Y = ABCBDAB => Longest Comman Subsequence is B C B
Dynamic Programming method : O ( n )
*/
package main
import "fmt"
func Max(more ...int) int {
max_num := more[0]
for _, elem := range more {
if max_num < elem {
max_num = elem
}
}
return max_num
}
func Longest(str1, str2 string) int {
len1 := len(str1)
len2 := len(str2)
//in C++,
//int tab[m + 1][n + 1];
//tab := make([][100]int, len1+1)
tab := make([][]int, len1+1)
for i := range tab {
tab[i] = make([]int, len2+1)
}
i, j := 0, 0
for i = 0; i <= len1; i++ {
for j = 0; j <= len2; j++ {
if i == 0 || j == 0 {
tab[i][j] = 0
} else if str1[i-1] == str2[j-1] {
tab[i][j] = tab[i-1][j-1] + 1
if i < len1 {
fmt.Printf("%c", str1[i])
}
} else {
tab[i][j] = Max(tab[i-1][j], tab[i][j-1])
}
}
}
fmt.Println()
return tab[len1][len2]
}
func main() {
str1 := "AGGTABTABTABTAB"
str2 := "GXTXAYBTABTABTAB"
fmt.Println(Longest(str1, str2))
//Actual Longest Common Subsequence: GTABTABTABTAB
//GGGGGTAAAABBBBTTTTAAAABBBBTTTTAAAABBBBTTTTAAAABBBB
//13
str3 := "AGGTABGHSRCBYJSVDWFVDVSBCBVDWFDWVV"
str4 := "GXTXAYBRGDVCBDVCCXVXCWQRVCBDJXCVQSQQ"
fmt.Println(Longest(str3, str4))
//Actual Longest Common Subsequence: ?
//GGGTTABGGGHHRCCBBBBBBYYYJSVDDDDDWWWFDDDDDVVVSSSSSBCCCBBBBBBVVVDDDDDWWWFWWWVVVVVV
//14
}
When I try to print out the subsequence when the tab gets updates, the outcome is duplicate.
I want to print out something like "GTABTABTABTAB" for the str1 and str2
Thanks in advance.
EDIT: It seems that I jumped the gun on answering this. On the Wikipedia page for Longest Common Subsequnce they give the pseudocode for printing out the LCS once it has been calculated. I'll put an implementation in go up here as soon as I have time for it.
Old invalid answer
You are forgetting to move along from a character once you have registered it as part of the subsequence.
The code below should work. Look at the two lines right after the fmt.Printf("%c", srt1[i]) line.
playground link
/*
X = BDCABA
Y = ABCBDAB => Longest Comman Subsequence is B C B
Dynamic Programming method : O ( n )
*/
package main
import "fmt"
func Max(more ...int) int {
max_num := more[0]
for _, elem := range more {
if max_num < elem {
max_num = elem
}
}
return max_num
}
func Longest(str1, str2 string) int {
len1 := len(str1)
len2 := len(str2)
//in C++,
//int tab[m + 1][n + 1];
//tab := make([][100]int, len1+1)
tab := make([][]int, len1+1)
for i := range tab {
tab[i] = make([]int, len2+1)
}
i, j := 0, 0
for i = 0; i <= len1; i++ {
for j = 0; j <= len2; j++ {
if i == 0 || j == 0 {
tab[i][j] = 0
} else if str1[i-1] == str2[j-1] {
tab[i][j] = tab[i-1][j-1] + 1
if i < len1 {
fmt.Printf("%c", str1[i])
//Move on the the next character in both sequences
i++
j++
}
} else {
tab[i][j] = Max(tab[i-1][j], tab[i][j-1])
}
}
}
fmt.Println()
return tab[len1][len2]
}
func main() {
str1 := "AGGTABTABTABTAB"
str2 := "GXTXAYBTABTABTAB"
fmt.Println(Longest(str1, str2))
//Actual Longest Common Subsequence: GTABTABTABTAB
//GGGGGTAAAABBBBTTTTAAAABBBBTTTTAAAABBBBTTTTAAAABBBB
//13
str3 := "AGGTABGHSRCBYJSVDWFVDVSBCBVDWFDWVV"
str4 := "GXTXAYBRGDVCBDVCCXVXCWQRVCBDJXCVQSQQ"
fmt.Println(Longest(str3, str4))
//Actual Longest Common Subsequence: ?
//GGGTTABGGGHHRCCBBBBBBYYYJSVDDDDDWWWFDDDDDVVVSSSSSBCCCBBBBBBVVVDDDDDWWWFWWWVVVVVV
//14
}

Resources