Narcissistic number using GO Issue

We had a task for Narcissistic number using GO, in this respect we written code as -

package main
import "fmt"
func main() {
    var number,tempNumber,remainder int
    var result int =0
    fmt.Scan(&number)

    tempNumber = number

    for {
        remainder = tempNumber%10
        result += remainder*remainder*remainder        
        tempNumber /= 10
        if(tempNumber==0){
            break  
        }
    }

    if(result==number){
         fmt.Println("True")
    }else{
        fmt.Println("False")
    }
}

We are not able to get desire output, wrong marked in bold -

153 True fine
1634 False not fine
155 False fine
2 False not fine
12456 False Fine
371 True Fine
8208 False not fine
92727 False not fine
1000 False fine
548834 True fine

Your calculation only works for inputs of 3 digits, as you take each digit to the power of 3 hardcoded.

You need to take it to the power of k, where k is the number of digits of the number. All the currently “correct” results you have are correct by accident, not by implementation.

thanks but can you please let us know where we had hardcoded it plz …

This line.

result +=result**power

This we need to write?

There is no power operator in Go. There is only math.Pow(), which would take float64 and return float64.

You need to implement an integer based power function on your own. Should be relatively straight forward.

1 Like

We tried below still same issue

var s int
    var sum int
    s = len(n)
    for i:=0;i<len(n);i++ {
        s=int(n[i]-'0')
        sum += s*s*s
    }

I don’t see where you are calculating a narcissistic number.


Wikipedia: Narcissistic number

package main

import "fmt"

func main() {
	var n int
	_, err := fmt.Scanln(&n)
	if err != nil || n < 0 {
		fmt.Println("False")
		return
	}

	digits := 0
	for m := n; m > 0; m /= 10 {
		digits++
	}

	sum := 0
	for m := n; m > 0; m /= 10 {
		digit := m % 10
		pow := 1
		for i := 1; i <= digits; i++ {
			pow *= digit
		}
		sum += pow
	}
	if sum == n {
		fmt.Println("True")
	} else {
		fmt.Println("False")
	}
}

thanks a lot :slight_smile:

Please do not provide solutions to obvious homework, no one will learn from that.

2 Likes

There is no such rule; that is not true.

Look at this solution, is this what you want ? :

https://play.golang.org/p/L5mjCnWeyay

our issue already resolved