I am kinda new in Go, I tried to find nth prime palindrome numbers but it always return 0, what did I do wrong here, output from my code should be 131.
For the sake of clearance, below I'll give sample of n and its return.
n: 1, Output: 2
n: 2, Output: 3
n: 3, Output: 5
n: 5, Output: 11
n: 6, Output: 101
n: 7, Output: 111
n: 8, Output: 151
n := 7
counter := 0
currNum := 1
palindromeNumber := 0
for counter < int(n) {
currNum
isPrime := false
for i := 2; i <= int(math.Sqrt(float64(currNum))); i {
if currNum%i == 0 {
isPrime = true
var number, remainder, temp int
var reverse int = 0
temp = currNum
// For Loop used in format of While Loop
for {
remainder = number % 10
reverse = reverse*10 remainder
number /= 10
if number == 0 {
// Break Statement used to exit from loop
break
}
}
if temp == reverse {
palindromeNumber = reverse
}
break
}
}
if !isPrime {
counter
}
}
return int64(palindromeNumber)
CodePudding user response:
Your main problem is the variable number. You create it and maybe you wanted to copy currNum into number before using number to calculate the reverted, but you are not doing that.
CodePudding user response:
Prime numbers are numbers that have only 2 factors: 1 and themselves, that means if a number n
is a prime number, it won't be divisible by any numbers in range from 2
to sqrt(n)
. But in your code, I see
if currNum%i == 0 {
isPrime = true
...
}
Why is currNum
prime if it's divisible by i
with i in range from 2
to sqrt(n)
? It's wrong. If currNum
meets this condition, it have to be a non-prime number.
Moreover, I don't see the assignment for var number
, so it will be its zero value 0
that also make palindromeNumber = 0
.
I think you should keep the prime check and the palindrome check in two separate functions to avoid confusions in your code (such as func isPrime
and func isPalindrome
).