splitEvery :: Int -> [a] -> [[a]]
splitEvery _ [] = []
splitEvery n xs = as : splitEvery n bs 
     where (as,bs) = splitAt n xs

check :: Int -> Bool
check value = not $ null $ filter (== value) $ takeWhile (<= value) [x*x|x<-[1..]]

solve :: [Int] -> Int
solve (n:d:rest) =
    func datas
    where
        datas = splitEvery d rest
        func :: [[Int]] -> Int
        func [] = 0
        func (x:xs) =
            l1 + l2
            where 
                l1 = func xs 
                l2 = length $ filter check $ do{
                    x2 <- xs;
                    return $ foldr (+) 0 $ do {
                        (i1,i2) <- zip x x2; 
                        return $ (i1 - i2) * (i1 - i2);
                    };
                }

main = interact $ show.solve.map read.words
