양의 정수 S0 의 각 아라비아 숫자들의 제곱의 합으로 양의 정수 S1을 만든다고 하자.
동일한 방법이라면, S1으로 S2를 만들 수 있고, 이 후로도 계속 만들 수 있다.
만약 어떤 i(i ≥ 1)에 대해서 Si = 1이라면, 최초의 S0를 Happy Number라고 부른다.
Happy Number가 아닌 수를 Unhappy Number라고 부른다.
예를 들어, 7에서 시작하게 되면 다음과 같은 일련의 순서를 가지게 되며
7, 49(=7^2), 97(=4^2+9^2), 130(=9^2+7^2), 10(=1^2+3^2), 1(=1^2),
따라서 7은 즐거운 수이다.
그리고 4는
4, 16(4^2), 37(1^2+6^2), 58(3^2+7^2), 89(5^2+8^2), 145(8^2+9^2),
42(1^2+4^2+5^2), 20(4^2+2^2), 4(2^2)의 순서로 반복되므로 Unhappy Number이다.
첫 라인은 인풋 케이스의 수 n이 주어지며 이후 n라인의 케이스가 주어진다.
각 테스트 케이스는 한 개의 양의 정수 N으로 구성되며 N은 10^9 보다 작다.
출력은 주어진 수 N이 Happy Number인지 Unhappy Number인지 여부에 따라 다음과 같이 출력한다.
N이 Happy Number라면 “Case #p: N is a Happy number.”
N이 Unhappy Number라면 “Case #p: N is an Unhappy number.”
p는 1부터 시작하는 케이스의 번호이며 각각의 케이스는 한 줄에 결과를 표시한다.
3
7
4
13
Case #1: 7 is a Happy number.
Case #2: 4 is an Unhappy number.
Case #3: 13 is a Happy number.
작성한 프로그램은 각각의 테스트케이스에 대해서 올바른 결과를 출력하여야 한다.
입력 후 결과 출력까지 걸리는 시간이 빠르면 빠를수록 좋다.
(* 이번 문제는 정확한 결과만큼이나 속도도 중요합니다)
프로그램에서 사용한 자료구조 및 알고리즘이 적절하여야 한다.
그 외 일반적인 코드 구조, 스타일, 에러/예외 처리 등이 적절할수록 좋다.
UVA 10591 문제이고, 이스트소프트 개발직군 샘플문제로 공개된 자료를 가져왔습니다. 채점기준을 준수한다면 난이도는 좀 더 상승될 것 같습니다.
69개의 풀이가 있습니다.
해피넘버, 언해피넘버 및 매 수행시의 이력을 다 저장하는 방법이 있지만, 모든 값을 캐싱하면서 캐싱한 값의 상태에 따라서 결과값을 찾습니다.
재귀호출하면서 상태를 pending --> 다음 결과에 따라 결과 확정하는 식으로 처리했습니다.
enum Happy {
case Happy, Unhappy, Pending
}
var cache = Dictionary<Int, Happy>()
cache[1] = .Happy
let next:(Int) -> Int = {n in
"\(n)".utf8.map{ (Int($0) - 48)*(Int($0) - 48) }
.reduce(0, combine:(+))
}
func test(n: Int) -> Bool {
if let r = cache[n] {
switch r {
case .Happy: return true
case .Unhappy: return false
default:
cache[n] = .Unhappy
return false
}
}
cache[n] = .Pending
let r = test(next(n))
cache[n] = r ? .Happy : .Unhappy
return r
}
func main(){
guard let input = readLine() else { return }
let data = input.characters.split(" ").map{ Int(String($0))! }
for (i, e) in data.enumerate() {
print("case #\(i+1) \(e) is \(test(e) ? "a Happy" : "an Unhappy") number.")
}
}
main()
아래는 같은 아이디어에 대한 파이썬 구현입니다.
# 0: unhappy
# 1: happy
# 2: pending
cache = {1: 1}
def f(n):
if n in cache:
if cache[n] == 1:
return True
cache[n] = 0
return False
cache[n] = 2
m = 0
while n > 0:
m += (n % 10)**2
n = n // 10
r = f(m)
if r:
cache[n] = 1
else:
cache[n] = 0
return r
p = int(input())
ins = []
for _ in range(p):
ins.append(int(input()))
for i, e in enumerate(ins):
print("Case #{}: {} is {} number.".format(
i+1, e, "a Happy" if f(e) else "an Unhappy"))
static void Main()
{
Stopwatch sw = new Stopwatch();
sw.Start();
int i, temp, digit, si, nHappyNum = 0;
HashSet<int> listHappy = new HashSet<int>() { 1 };
HashSet<int> listUnhappy = new HashSet<int>();
List<int> listCurrent = new List<int>();
for (int s0 = 1; s0 < 10000001; s0++)
{
if (listCurrent.Count > 0) listCurrent.Clear();
temp = s0;
while (true)
{
si = 0;
do
{
digit = temp % 10;
si += digit * digit;
}
while ((temp /= 10) > 0);
if (listUnhappy.Contains(si) || listCurrent.Contains(si))
{
for (i = 0; i < listCurrent.Count; i++)
listUnhappy.Add(listCurrent[i]);
break;
}
if (listHappy.Contains(si))
{
nHappyNum++;
for (i = 0; i < listCurrent.Count; i++)
listHappy.Add(listCurrent[i]);
break;
}
listCurrent.Add(si);
temp = si;
}
}
Console.WriteLine(string.Format("Elapsed Time : {0}", sw.Elapsed));
Console.WriteLine(string.Format("Number of HappyNumber (1 ~ 10000000) : {0}", nHappyNum));
}
#Python 3.5
T=[3,7,4,13]
def happyNumber(d) :
numbers=[]
unhappy=[]
l=d
while(l != "1" ) :
for i in range(len(l)) :
a = int(l[i])*int(l[i])
numbers.append(a)
l = str(sum(numbers))
del numbers[0:len(numbers)]
if l == d : return False
for i in unhappy :
if i == l : return False
unhappy.append(l)
return True
if len(T)-1 != T[0] :
print("영혼이 비정상...")
exit()
else : T.pop(0)
#T=range(2,10000) #속도테스트
for i,d in enumerate(T) :
if happyNumber(str(d)) :
print("Case #"+(str(i+1))+": %s is a Happy number."%d)
else :
print("Case #"+(str(i+1))+": %s is an Unhappy number."%d)
//class
//HappyNumber.isHappyNumber(7) is True;
//HappyNumber.isHappyNumber(42) is false;
public class HappyNubmer
{
public static bool isHappyNumber(int number)
{
bool isHappy = false;
List<int> numberList = new List<int> ();
int nextNumber = number;
while (true) {
nextNumber = getNextNumber (nextNumber);
if (numberList.Contains (nextNumber)) {
isHappy = false;
break;
}
if (nextNumber == 1) {
isHappy = true;
break;
}
numberList.Add (nextNumber);
}
return isHappy;
}
public static int getNextNumber(int number)
{
List<int> splitedNumbers = splitNumber (number);
int nextNumber = 0;
foreach (int splitedNumber in splitedNumbers) {
nextNumber += square (splitedNumber);
}
return nextNumber;
}
public static List<int> splitNumber(int number)
{
List<int> splitedNumber = new List<int> ();
int splitNumber = number;
while (true) {
splitedNumber.Insert(0,splitNumber % 10);
if (splitNumber < 10)
break;
splitNumber = splitNumber / 10;
}
return splitedNumber;
}
public static int square(int number)
{
return number*number;
}
}
//nunit test
[TestFixture]
public class HappyNumberTest {
[Test,Sequential]
public void isHappyNumberTest([Values(7,42)]int n,[Values(true,false)]bool r)
{
bool check7 = HappyNubmer.isHappyNumber (n);
Assert.AreEqual (r, check7);
}
[Test]
public void getNextNumberTest()
{
int number1 = 7;
int nextNumber = HappyNubmer.getNextNumber (number1);
Assert.AreEqual (49, nextNumber);
}
[Test]
public void splitNumberTest()
{
int number1 = 130;
List<int> result = HappyNubmer.splitNumber (number1);
Assert.AreEqual (1, result [0]);
Assert.AreEqual (3, result [1]);
Assert.AreEqual (0, result [2]);
Assert.AreEqual (3, result.Count);
}
[Test]
public void squareTest()
{
int number1 = HappyNubmer.square (5);
Assert.AreEqual (number1, 25);
}
}
공부중인 ttd를 활용해서 한번..
def check_num(n, List):
if n == 1:
return 1
Next_n = sum([int(x) ** 2 for x in list(str(n))])
if Next_n in List:
return 0
else:
List.append(Next_n)
return check_num(Next_n, List)
if __name__ == '__main__':
case_n = input('Input case number: n = ')
for i in range(int(case_n)):
while True:
n = int(input('Number: '))
if n <= pow(10,9):
break
decision = check_num(n, [])
print('Happy Number' * decision + 'Unhappy Number' * (not decision))
초짜입니다. ^^ 문자열을 아직 잘 다루지 못 해 수학 함수로만 짜 봤습니다. 제대로 짰는지 모르겠네요. 일단 test 결과는 제대로 나오는데...
# tried to find happy number only with math functions
import math
n = int(input("how many happy number candidates? "))
while n > 0:
a = int(input("type in happy number candidate: "))
c = 10
while c >=10:
b = math.floor(math.log10(a))
c = 0
while b >= 0:
c = c + ((a // (10 ** b)) ** 2)
a = a % (10 ** b)
b = b - 1
a = c
if c == 1:
print ("happy")
else:
print ("unhappy")
n = n - 1
Python으로 작성
# find happy number
def is_happy_num(s0, history=[]):
s1 = sum(map(lambda x:x*x, [int(i) for i in repr(s0)]))
if s1 == 1:
return True
elif s1 in history:
return False
else:
history.append(s1)
return is_happy_num(s1)
# Test case
for i, num in enumerate([3,7,4,13]):
case = "Case #%d: %d is " % (i, num)
result = "Happy number." if is_happy_num(num, []) else "an Unhappy number."
print(case + result)
결과
Case #0: 3 is an Unhappy number.
Case #1: 7 is Happy number.
Case #2: 4 is an Unhappy number.
Case #3: 13 is Happy number.
Haskell로 작성
import Data.Char (digitToInt)
import Control.Monad (join)
is_happy_number n history
| sumnum == 1 = True
| sumnum `elem` history = False
| otherwise = is_happy_number sumnum (sumnum:history)
where sumnum = sum [(digitToInt x)^2 | x<-show(n)]
test_happy_number n = join [show(n), " is ", (if is_happy_number n [] then "a Happy" else "an Unhappy"), " number."]
main = do
mapM_ putStrLn $ map test_happy_number [3,7,4,13]
결과
3 is an Unhappy number.
7 is a Happy number.
4 is an Unhappy number.
13 is a Happy number.
def happy(a) : aa =[] n=a
while True: b=n s=0 while n>0 : s+= pow( n%10,2) n/= 10
if s == 1 : print str(a) + " is happy number." break elif s in aa: print str(a) + " is unhappy number." else : aa.append(b) n = s
a = [7,4,13]
for i in a: happy(i)
C언어 입니다.! 다른 분들의 경우를 참고해서 풀어봤어요~!(해쉬테이블) 더 분발해야 겠습니다!
#include <stdio.h>
#define BK 1000
#define SL 1
int hashtable[BK][SL];
int Hash(int key)
{
return key % 10;
}
void AddNum(int num)
{
int bucket = Hash(num);
if(hashtable[bucket][0] == 0){
hashtable[bucket][0] = num;
}
}
int FindNum(int num)
{
int bucket = Hash(num);
return (hashtable[bucket][0] == num);
}
int main()
{
int t, TC = 5;
for(t=0; t<TC; t++){
int N, sN;
int sum, digit;
scanf("%d", &N);
sN = N;
memset(hashtable, 0, sizeof(hashtable));
while(1){
sum = 0;
do
{
digit = N % 10;
sum += digit * digit;
}while((N/=10) > 0);
N = sum;
//printf("N = %d \n", N);
if(N == 1) break;
else if((FindNum(sum)) == 1) break;
else AddNum(sum);
}
if(N == 1) printf("Case #%d : %d is Happy Number.\n", t+1, sN);
else printf("Case #%d : %d is Unhappy Number.\n", t+1, sN);
}
return 0;
}
def isHappy(n):
l=[n]
while 1:
next = sum(int(x)**2 for x in str(n))
if next==1 : return True
if next in l : return False
l.append(next);n=next
case =[int(raw_input()) for i in range(input())]
for i,c in enumerate(case):
print 'Case #%d:%d is a %s number'%(i+1, c, ['Unhappy','Happy'][isHappy(c)])
def f(x):
r = sum([ ( r * r ) for r in [ int(_) for _ in str(x) ] ])
return f(r) if len(str(r)) > 1 else r
def hnvalid(x):
return ( '%d is a happy number.' % x ) if f(x) == 1 else ( '%d is an unhappy number.' % x )
print hnvalid(3)
print hnvalid(7)
print hnvalid(4)
print hnvalid(13)
Python 2.7 에서 작성하였습니다.
Ruby
require 'set'
nxt = ->n { n.digits.sum {|e| e**2 } }
chk = ->n,seq=[1].to_set { n=nxt[n] while seq.add?(n); n == 1 ? " H" : "n Unh" }
chk_happy = ->nth,n=gets.to_i { "Case ##{nth}: #{n} is a#{chk[n]}appy Number." }
happy_checker = -> { puts (1..gets.to_i).map(&chk_happy) }
Test
expect(nxt[15]).to eq 26
$stdin = StringIO.new("3\n4\n7\n13\n")
expect{happy_checker.call}.to output("Case #1: 4 is an Unhappy Number.\n" +
"Case #2: 7 is a Happy Number.\n" +
"Case #3: 13 is a Happy Number.\n").to_stdout
변환중의 값을 캐쉬하여 동일한 값이 있으면 False 처리하기 때문에 속도가 빠릅니다
from functools import reduce
def ishappy(n:int) -> bool:
init = n
temp = () #캐쉬
while True:
n = sum(int(x)**2 for x in str(n))
if n in temp:
return False
else:
temp += n,
if n == init:
return False
elif n == 1:
return True
%timeit ishappy(185719837494182639811762347812364987102365198239841293471293068412083461203) #10000 loops, best of 3: 61.8 µs per loop
import time
def isHappy(n):
li = []
while 1:
n = sum(int(y)**2 for y in str(n))
if n in li and n != 1:
# print('no')
break
elif n == 1:
# print('yes')
break
li.append(n)
if __name__ == '__main__':
a = time.time()
for x in range(1,1000000):
isHappy(x)
print(time.time()-a)
컴파일 언어가 역시 빠르네요;; 백만 기준으로 25.94032382965088초 나옵니다. i7-6700HQ 파이썬 3.5.1
===
import time, itertools
from multiprocessing import Process, Queue
CORE = 8
MULTIPLY = 1000000
def isHappy(n):
li = []
while 1:
n = sum(int(y)**2 for y in str(n))
if n in li and n != 1:
return False
elif n == 1:
return True
li.append(n)
def happyProcess(start, end, output):
li = []
for x in range(start, end):
li.append(isHappy(x))
output.put(li)
if __name__ == '__main__':
a = time.time()
procs = [];output = [];result = []
for x in range(CORE):
output.append(Queue())
exec('procs.append(Process(target = happyProcess, args = ('+str(x*MULTIPLY)+','+str((x+1)*MULTIPLY)+', output['+str(x)+'])))')
for x in procs:
x.start()
print(x)
for x in range(CORE):
exec('result.append(output['+str(x)+'].get())')
for x in range(CORE):
exec('output['+str(x)+'].close()')
for x in procs:
x.join()
result = list(itertools.chain(*result))
print(','.join((str(time.time()-a), str(len(result)))))
print('result stored in \'result\' object')
멀티프로세스 버전입니다. cpu 점유율 100프로까지 치솟네요. 작업 적으면 프로세스 줄이면 더 빠릅니다. 저는 하이퍼스레딩 켜놔서 우선 8코어로 놨습니다. 총 계산량은 MUTIPLY 곱하기 CORE 이니 하나 줄이면 하나를 올려야 합니다. 이거 잊어먹고 MULTIPLY에 천만 넣었다가 8천만개 계산했네요;;
577.9152545928955초, 80000000개
def check_num(n, List): if n == 1: return 1
Next_n = sum([int(x) ** 2 for x in list(str(n))])
if Next_n in List:
return 0
else:
List.append(Next_n)
return check_num(Next_n, List)
if name == 'main': case_n = input('Input case number: n = ') for i in range(int(case_n)): while True: n = int(input('Number: ')) if n <= pow(10,9): break decision = check_num(n, []) print('Happy Number' * decision + 'Unhappy Number' * (not decision))
#파이썬3.5.1
def happy(n):
n = int(n)
numlist = set()
numlist.add(n)
old = None
while True:
new = len(numlist)
if new == old:
return False
old = len(numlist)
n = eval('**2+'.join(str(n)+'0'))
if n == 1:
return True
numlist.add(n)
case = []
n = int(input())
for i in range(n):
case.append(int(input()))
for i in range(len(case)):
ans = happy(case[i])
if ans:
print('Case #%d : %d is a Happy number.' % (i+1,case[i]))
else:
print('Case #%d : %d is a Unhappy number.' % (i + 1, case[i]))
sum.fun = function(x){
tmp = c()
for(i in 1:nchar(x))
{
tmp[i] = as.numeric(substr(x, i, i))
}
tmp1 = sum(tmp^2)
return(tmp1)
}
sum2.fun = function(x){
a1 = input = x
for(j in 1:(10^9)){
# cat("input : ", input, ", j : ", j, "th iter , x : ", a1[j], " \n")
a2 = sum.fun(a1[j])
a1 = c(a1, a2)
if(a2 == input) {return(paste0("when case : ", x, ", result : " ,"UNHAPPY, with ", j, "th iterations")); break}
if(a2 == 1) {return(paste0("when case : ", x, ", result : ", "HAPPY, with ", j, "th iterations")); break}
if(sum(a1[-1] %in% a2) > 1) {return(paste0("when case : ", x, ", result : UNHAPPY with infinite iterations")); break}
}
}
y = sample(size = 100, c(1:2000), replace = F)
system.time(aa <- sapply(y, sum2.fun))
R로 작성하였습니다. 100개의 숫자에 대해 153초가 나오네요. 다른 분들에 비해 많이 느린 듯 합니다.
[1] "when case : 1278, result : UNHAPPY with infinite iterations"
[2] "when case : 1680, result : UNHAPPY with infinite iterations"
[3] "when case : 1289, result : UNHAPPY with infinite iterations"
[4] "when case : 121, result : UNHAPPY with infinite iterations"
[5] "when case : 98, result : UNHAPPY with infinite iterations"
[6] "when case : 684, result : UNHAPPY with infinite iterations"
....
파이썬3 반복되는경우를 try문으로 처리해보았습니다.
def Happy_num(a):
try:
Sum = 0
for i in str(a):
Sum += int(i)*int(i)
if Sum == 1:
return "is a Happy number."
else:
return Happy_num(Sum)
except:
return "is an Unhappy number."
trynum = 0
while 1:
num = int(input())
trynum += 1
print('Case #', trynum,':', num, Happy_num(num))
C#으로 작성했습니다. Hashset으로 구현했습니다.
using System.Collections.Generic;
public static class Question098FindHappyNumbers
{
// time taken: 00:05:27:21
public static void Answer()
{
var output1 = FindHappyNumbers(3);
var output2 = FindHappyNumbers(7);
var output3 = FindHappyNumbers(4);
var output4 = FindHappyNumbers(13);
}
public static bool FindHappyNumbers(int input)
{
var curr = input;
var outputs = new HashSet<int>();
while(true)
{
outputs.Add(curr);
var index = curr.ToString().Length;
var last = curr;
curr = 0;
for (int i = 0; i < index; i++)
curr += int.Parse(last.ToString()[i].ToString())
* int.Parse(last.ToString()[i].ToString());
if (outputs.Contains(curr)) return false;
if (curr == 1) return true;
}
}
}
이 문제를 해결하기 위해서 과정을 simulate 하면서 여태까지 나왔던 숫자들을 기억(캐쉬)해줍니다. 만약 1이 나오기전에 나왔던 숫자가 또 나온다면 Unhappy number입니다. C++ code입니다.
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
vector<int> cache;
bool chk(int number){
while (true){
if (number == 1) return true;
if (find(cache.begin(),cache.end(),number) != cache.end()) return false;
cache.push_back(number);
int temp = number;
number = 0;
while (temp){
number += (temp%10)*(temp%10);
temp /= 10;
}
}
return false;
}
int main(){
int n;
scanf("%d",&n);
for (int i = 1; i <= n; i++){
cache.clear();
int number;
scanf("%d",&number);
if (chk(number)){
printf("Case #%d: %d is a Happy number.\n",i,number);
}else{
printf("Case #%d: %d is an Unhappy number.\n",i,number);
}
}
}
import java.util.Scanner;
public class test {
public static void main(String[] argv) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] k = new int[n];
for(int i =0; i < n; i++){
k[i] = sc.nextInt();
}
for(int i =0 ; i<k.length; i++){
if(happyNum(k[i])){
System.out.println("\nCase #"+i+": "+ k[i] + " is a Happy number");
}else{
System.out.println("\nCase #"+i+": "+ k[i] + " is a UnHappy number");
}
}
}
public static boolean happyNum(int num){
String splitNum = String.valueOf(num);
boolean isRoop = true;
boolean isHappy = false;
while(isRoop){
int value = 0;
for(int i = 0; i < splitNum.length(); i ++){
value += Math.pow(Integer.parseInt(splitNum.substring(i, i+1)), 2);
}
if(value < 10){
isRoop = false;
if(value == 1){
isHappy = true;
}else{
isHappy = false;
}
}else{
splitNum = String.valueOf(value);
}
}
return isHappy;
}
}
def is_happy(n):
s_list=[]
while 1:
s=sum([int(x)**2 for x in str(n)]) #제곱의 합
'''
s가 1이면 True, 같은 s가 또 나오면 False
'''
if s==1: return True
elif s in s_list: return False
else:
s_list.append(s)
n=s
how_much=int(input('입력의 수? '))
inputs=[]
for k in range(how_much):
inputs.append(int(input('수를 입력하세요 : ')))
for k in range(how_much):
if bool(is_happy(inputs[k]))==True:
print("Case #%d: %d is a Happy Number" %(k+1, inputs[k]))
else:
print("Case #%d: %d is an Unhappy Number" %(k+1, inputs[k]))
def HN(composition, x):
j = 0
result = 0
while j < composition:
for i in range(len(str(x))):
result += int(str(x)[i])**2
x = result
result = 0
j += 1
return x
#main
casenum = int(input('인풋 케이스의 수 :'))
hub = []
for i in range(casenum):
hub.append(int(input()))
for i in range(casenum):
for j in range(100):
if HN(j, hub[i]) == 1:
print('Case #{}: {} is the happy number.'.format(i+1,hub[i]))
break
if HN(j, hub[i]) == 4:
print('Case #{}: {} is the unhappy number.'.format(i+1,hub[i]))
break
#include <iostream>
#include <cmath>
#include <iomanip>
#include <ctime>
using namespace std;
bool is_happy(int num);
int reverse_int(int num);
int main()
{
clock_t startTime;
int size;
int *numbers;
cout << "The number of case: ";
cin >> size;
numbers = new int[size];
cout << "Numbers: ";
for (int i = 0; i < size; i++) {
cin >> *(numbers + i);
}
startTime = clock();
cout << "==================================" << endl;
for (int i = 0; i < size; i++) {
cout << "Case #" << setw(3) << i + 1 << ": " <<*(numbers + i)<< endl;
if (is_happy(*(numbers + i)))
cout << endl << *(numbers + i) << " is a Happy number." << endl << endl;
else
cout << endl << *(numbers + i) << " is an Unhappy number." << endl << endl;
}
delete[] numbers;
cout << "Calculation time: " << double(clock() - startTime) / (double)CLOCKS_PER_SEC << " seconds." << endl;
return 0;
}
bool is_happy(int num)
{
int temp = num, power_sum = 0;
int table[729]; // Happy number를 판별할 때 사용하기 위한 배열
for (int i = 0; i < 729; i++) {
while (temp) {
power_sum += (temp % 10)*(temp % 10);
temp /= 10;
}
table[i] = power_sum;
cout << power_sum << " ";
if (power_sum == 1)
return true;
for (int j = 0; j < i; j++) {
if (power_sum == table[j] || reverse_int(power_sum) == table[j])
return false;
}
temp = power_sum;
power_sum = 0;
}
}
int reverse_int(int num) {
int result = 0;
while (num != 0) {
result *= 10;
result += (num % 10);
num /= 10;
}
return result;
}
The number of case: 5
Numbers: 7 4 13 2847 958375
==================================
Case # 1: 7
49 97 130 10 1
7 is a Happy number.
Case # 2: 4
16 37 58 89 145 42 20 4 16
4 is an Unhappy number.
Case # 3: 13
10 1
13 is a Happy number.
Case # 4: 2847
133 19 82 68 100 1
2847 is a Happy number.
Case # 5: 958375
253 38 73 58 89 145 42 20 4 16 37
958375 is an Unhappy number.
Calculation time: 0.009 seconds.
// 즐거운 수 - C#
// 무한 재귀 함수는 catch가 안 돼요
using System;
namespace HappyhappyImhappy
{
class Program
{
static bool Ishappy(int num, int def, int count)
{
if (count == 8500) // 예측되는 StackOverflowExeption 발생 타이밍에서 안됨 반환.
return false;
int digit = (int)Math.Log10(num) + 1;
int[] row = new int[digit];
for (int i = 0; i < digit; i++)
row[i] = num / (int)Math.Pow(10, i) % 10;
int result = 0;
foreach (int n in row)
result += n * n;
if (result == 1)
return true;
else if (result == def)
return false;
else
return Ishappy(result, def, ++count);
}
static void Main(string[] args)
{
Console.WriteLine("READY >>>");
int attempt = int.Parse(Console.ReadLine());
int[] nums = new int[attempt];
for (int i = 0; i < attempt; i++)
nums[i] = int.Parse(Console.ReadLine());
for (int i = 0; i < attempt; i++)
Console.WriteLine("Case #{0}: {1} is {2}", i + 1, nums[i], Ishappy(nums[i], nums[i], 0) ? "a Happy number." : "an Unhappy number.");
}
}
}
def HappyNumber(n):
k = n
a = 0
while n != a:
a = 0
for i in str(k):
a += int(i)**2
if a == 1:
print("%d is Happy Number"%n)
break
else:
k = a
if a != 1:
print("%d is Unhappy Number"%n)
HappyNumber(7)
HappyNumber(4)
HappyNumber(13)
중간에 싸이클이 있으면 무한히 반복되기 때문에 반드시 싸이클을 검사해야 정확한 답을 알 수 있습니다.
변환을 반복하면서 한 번 나왔던 숫자들을 history에 저장합니다.
만약 1이 나오거나, happy로 이미 판명된 수가 나오면 history에 있는 수는 모두 happy입니다.
반면 같은 수가 다시 나오거나(싸이클), unhappy로 이미 판명된 수가 나오면 history에 있는 수는 모두 unhappy입니다.
def isHappy(n):
global happyset, unhappyset
def dsum(n):
return 0 if n == 0 else (n % 10)**2 + dsum(n // 10)
history = set()
while True:
history.add(n)
n = dsum(n)
if n== 1 or n in happyset:
happyset |= history
return True
if n in history or n in unhappyset:
unhappyset |= history
return False
happyset, unhappyset = set(), set()
N = 100000
print(sum([isHappy(n) for n in range(N)]), 'happy numbers under ', N) # 14376
자바 연습
import java.util.HashSet;
public class test {
static HashSet<Integer> happySet = new HashSet<Integer>();
static HashSet<Integer> unhappySet = new HashSet<Integer>();
public static int dsum(int n) {
if (n == 0) {
return 0;
} else {
int d = n % 10;
return d * d + dsum(n / 10);
}
}
public static boolean isHappy(int n) {
HashSet<Integer> currentSet = new HashSet<Integer>();
while (true) {
currentSet.add(n);
n = dsum(n);
if (n == 1 || happySet.contains(n)) {
happySet.addAll(currentSet);
return true;
}
if (currentSet.contains(n) || unhappySet.contains(n)) {
unhappySet.addAll(currentSet);
return false;
}
}
}
public static void main(String[] args) {
int N = 100;
int cnt = 0;
for (int i = 2; i < N; i++) {
if (isHappy(i)) {
cnt++;
}
}
System.out.printf("%d happy numbers under %d\n", cnt, N);
}
}
def happyCh(num1):
num2 = num1
num1 = sum([x ** 2 for x in (list(map(int, str(num1))))])
while num1 >= 10:
num1 = sum([x ** 2 for x in (list(map(int, str(num1))))])
if num1 == 1:
print(num2,'is a Happy number.')
else:
print(num2, 'is an Unhappy number.')
cnt = input('첫 라인은 인풋 케이스의 수 n : ')
input_arr = []
if cnt == '' or cnt == 0:
exit()
for i1 in range(0, int(cnt)):
input_arr.append(input('케이스 :'))
for n1 in input_arr:
happyCh(int(n1))
import time
t = time.time()
#inp = '20 15 7 4 13 15 3 2 3 4 5 88 79 8 21 3 5 55 7454 45 5'.split()
inp = ['100000'] + [str(i) for i in range(2, 100002)]
happynum = set([])
unhappynum = set([])
def isHappy(n):
global happynum
global unhappynum
cache = set(n)
while 1:
n = str(sum([int(i)**2 for i in n]))
if n in {'1'} | happynum:
happynum.update(cache)
return 'Happy'
elif n in cache | unhappynum:
unhappynum.update(cache)
return 'Unhappy'
cache.add(n)
for i in range(1, int(inp[0])+1):
print('Case #%d: %s is a %s number' %(i, inp[i], isHappy(inp[i])))
print(time.time()-t)
파이썬 3.6
import time
def inputdata():
N = int(input(''))
data = [input('') for i in range(N)]
return data
def happynum(n):
Si,tmp = 0,list(n)
while Si != 1:
Si = sum([ int(i)**2 for i in tmp])
tmp = list(str(Si))
# 1이 아닌 자연수중 가장 작은 제곱수는 4이므로, unhappynumber의 Si는 4로 수렴한다.
if Si == 4:
return "%s is an Unhappy number."%n
return "%s is an Happy number."%n
def main(data):
for n,value in enumerate(data):
print("Case #%d: %s"%(n+1,happynum(value)),"\n")
if __name__ == "__main__":
data = inputdata()
startTime = time.time()
main(data)
print("runtime: %fs"%(time.time() - startTime))
*결과값
4
7
4
13
56603269873654
Case #1: 7 is an Happy number.
Case #2: 4 is an Unhappy number.
Case #3: 13 is an Happy number.
Case #4: 56603269873654 is an Unhappy number.
runtime: 0.112007s
digit square에 의해 1000초과일때 항상 감소수열이므로 미리 1000개의 happy값을 리스트로 만들고 1000보다 큰 수는 digitsquare하여 1000보다 작게 만든 후 리스트에서 불러왔습니다. test case 100000개 2초내로 나오네요.
import time
import random
def digitsquare(n):
result = 0
while n // 10:
result += (n % 10) * (n % 10)
n = n // 10
result += n * n
return result
def happy(n):
seq = [n]
def place(a, n):
index = 0
b = int(len(a) / 2)
if len(a) == 1:
if a[0] <= n:
index += 1
elif n < a[b]:
index += place(a[:b], n)
else:
index += place(a[b:], n) + b
return index
while 1:
n = digitsquare(n)
if n == 1:
return "happy"
c = place(seq, n)
seq.insert(c, n)
if c != 0:
if not(seq[c]-seq[c-1]):
return "unhappy"
a = [random.randint(1, 1000000000) for i in range(1000000)]
start_time = time.time()
b = [happy(i) for i in range(1, 1001)]
for i in a:
while i > 1000:
i = digitsquare(i)
print(b[i-1])
print(time.time()- start_time)
각 자릿수를 추출하고 제곱해서 합한뒤(nextNum) list에 저장합니다. list에는 처음 입력숫자도 저장합니다. list의 해당 숫자가 한번 더 나온다면 unhappy Number 또는 nextNum이 1이 되면 HappyNum이 됩니다.
using System;
using System.Collections.Generic;
namespace CSharp_Test
{
class Program
{
static void Main(string[] args)
{
List<int> list = new List<int>();
int testcase = int.Parse(Console.ReadLine());
for(int i = 1; i <= testcase; i++)
{
int n = int.Parse(Console.ReadLine());
list.Add(n);
//각 자릿수의 제곱
while (true)
{
Console.WriteLine(n);
int nextNum = 0;
bool flag = false;
int divideNum = 1;
while (n / divideNum >= 1)
{
int tempNum;
tempNum = (n % (divideNum * 10) / divideNum);
tempNum *= tempNum; //제곱
nextNum += tempNum;
Console.WriteLine("자릿수 {0}", tempNum); //디버그
divideNum *= 10;
}
for(int j = 0; j < list.Count; j++)
{
//이미 있는 수가 나왔다면
if (list[j] == nextNum)
flag = true;
}
if (nextNum == 1) //1이 나왔다면
{
Console.WriteLine("Case #{0} : is a Happy Number", i);
break;
}
else if(flag == true)
{
Console.WriteLine("Case #{0} : is an Unhappy Number", i);
break;
}
list.Add(nextNum);
n = nextNum;
}
}
}
}
}
def happy(a):
new = eval(("**2+".join(str(a[len(a)-1]) ))+"**2")
if new in a:
return print(str(a[0])+" is a unhappy number")
elif new==1:
return print(str(a[0])+" is a happy number")
else:
happy(a+[new])
# include <stdio.h>
void happy(int n[], int nn) {
int a = n[nn-1], SqrSum = 0, Mul = 1;
int re[1000];
while (a >= 1) {
SqrSum += (a % 10)*(a % 10);
a = a/10;
}
for (int i = 0; i < nn; i++) {
Mul *= (SqrSum - n[i]);
}
if (SqrSum == 1){
printf("%d is a happy number\n", n[0]);
}else if(Mul==0){
printf("%d is an unhappy number\n", n[0]);
}
else {
for (int i = 0; i < nn; i++) {
re[i] = n[i];
}
re[nn]=SqrSum;
happy(re, nn+1);
}
}
int main() {
int m[1];
printf("숫자를 입력하시오.\n");
scanf_s("%d", m);
happy(m, 1);
return(0);
}
b=[]
def happy_num(x):
b.append(x)
a=[int(i) for i in list(str(x))]
a=sum([i**2 for i in a])
if a==1 : print(b[0], 'is happy number.')
elif a in b : print(b[0], 'is unhappy number.')
else : happy_num(a)
Swift입니다. 숫자 이력을 비교해서 반복되는 숫자가 나오면 Happy Number가 아닌 것으로 판단했습니다.
import Foundation
var happyPattern = Set<Int>()
var unHappyPattern = Set<Int>()
func isHappyNumber(_ givenNumber: Int) -> Bool {
var number = givenNumber
var numberHistory = [Int]()
var nextNumber = 0
while nextNumber != 1 {
nextNumber = Array(String(number)).reduce(0, { let digit = Int(String($1))!; return $0 + digit * digit })
if happyPattern.contains(nextNumber) {
for history in numberHistory {
happyPattern.insert(history)
}
return true
} else if unHappyPattern.contains(nextNumber) {
for history in numberHistory {
unHappyPattern.insert(history)
}
return false
} else {
if nextNumber != 1 {
if (numberHistory.filter {$0 == nextNumber}.count == 0) {
numberHistory.append(nextNumber)
number = nextNumber
} else {
return false
}
}
}
}
return true
}
print("7 - \(isHappyNumber(7))")
print("4 - \(isHappyNumber(4))")
print("13 - \(isHappyNumber(13))")
print("1234569789 - \(isHappyNumber(1234569789))")
print("9999999 - \(isHappyNumber(9999999))")
static int f(int num) { // 다음 값을 구하는 메서드
int ans = 0;
while(num>0) {
ans += Math.pow(num%10, 2);
num /= 10;
}
return ans;
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
for (int i=0; i<t; i++) {
int x = Integer.parseInt(br.readLine()); // 초기값
int tmp = x;
while(true) {
tmp = f(tmp);
if(tmp == x) { // 메서드를 돌리다가 tmp가 초기값이 될 때
System.out.println(x + " is unhappy");
break;
} else if (tmp == 1) { // 1이 될 때
System.out.println(x + " is happy");
break;
} else // 그것도 아니면 계속 돌림
continue;
}
}
} // 자바입니다
def happyNUm(N:Int): Unit ={
var set = Set[Int]()
def loop(num:Int): Unit ={
println(set)
num match {
case 1 => println(s"${N} is Happy number")
case _ => {
if(set(num)) println(s"${N} is Unhappy number")
else {
set += num
loop(num.toString.map(v => (v.toInt - 48)*(v.toInt - 48)).sum)
}
}
}
}
loop(N)
}
for를 통해 100만번을 돌려봤지만 모두 1과 4로 귀결됬습니다.
1이면 해피넘버 4이면 언해피넘버가 됩니다.
1~100만까지의 모든 수를 체크했을시 3초정도 걸립니다.
import java.util.Scanner;
public class Count {
public static void main(String[] args) {
int n = new Scanner(System.in).nextInt();
System.out.println(CheckHappy(n) ? n + " is a Happy number." : n + " is an Unhappy number.");
}
private static boolean CheckHappy(int n) {
int sum = 0;
for (int i = 0; i < (n + "").length(); i++)
sum += Math.pow(Integer.valueOf((n + "").substring(i, i + 1)), 2);
return sum == 1 ? true : sum == 4 ? false : CheckHappy(sum);
}
}
def HappyNumber(n):
Num = []
for x in range(0,n):
Num.append(int(input("\n number : ")))
for n in Num:
lis,n1 = [],n
while True:
n = sum(int(i)**2 for i in list(str(n)))
if n == 1:
print("%d is a Happy number." %(n1))
break
elif n in lis:
print("%d is an Unhappy number." %(n1))
break
lis.append(n)
eachsq = lambda x: sum(int(i)**2 for i in str(x))
n = int(input())
m = []
for _ in range(n): m.append(int(input()))
hpn,nhn,tmp = set(),set(),[]
for i in range(n):
tmp.clear()
tmp.append(m[i])
while 1:
tmp.append(eachsq(tmp[-1]))
if tmp[-1] == 1 or tmp[-1] in hpn:
hpn |= set(tmp)
print('Case #{}: {} is Happy number.'.format(i+1,m[i]))
break
elif tmp[-1] == m[i] or tmp[-1] in nhn:
nhn |= set(tmp)
print('Case #{}: {} is UnHappy number.'.format(i+1,m[i]))
break
happy.number <- function(x){
orig <- x
x <- as.character(x)
x_split <- as.numeric(strsplit(x, '')[[1]])
x <- sum(x_split ^ 2)
#print(x)
while(x != orig){
x <- as.character(x)
x_split <- as.numeric(strsplit(x, '')[[1]])
x <- sum(x_split ^ 2)
#print(x)
if (x == 1){
temp_happy <- paste(orig, ' is a Happy number.', sep = '')
return(temp_happy)
}
}
temp_unhappy <- paste(orig, ' is an Unhappy number.', sep = '')
return(temp_unhappy)
}
def happy(n):
happylist=[]
k=n
while True:
sqrsum=0
for i in str(k):
sqrsum+=int(i)**2
if sqrsum==1:
return True
elif sqrsum in happylist:
return False
else:
k=sqrsum
happylist.append(sqrsum)
continue
checklist=[]
num=int(input("How many numbers to check?: "))
for i in range(num):
number=int(input("Input number ({0}): ".format(i+1)))
checklist.append(number)
for i in range(len(checklist)):
if happy(checklist[i]):
print("Case #{0}: {1} is a Happy number.".format(i+1,checklist[i]))
else:
print("Case #{0}: {1} is an Unappy number.".format(i+1,checklist[i]))
def isHappy(n):
def f(k):
s = 0
while k > 0:
s += (k % 10) ** 2
k = k // 10
return s
m = n
while True:
m = f(m)
if m == 1:
print("HAPPY")
return
if m == n:
print("UNHAPPY")
return
Python 3.7
class HappyNum:
def __init__(self, num: int):
self.num = num
self.pool = [] # 각 자리수 제곱의 합이 저장될 시퀀스
def getstatstr(self):
next_num = self.num
while next_num not in self.pool: # 시퀀스 내 숫자가 없으면
self.pool.append(next_num) # 추가 하고
next_num = HappyNum._getnext(next_num) # 다음 시퀀스 계산
# 1인 경우 a happy 아니면 an unhappy
return f"{self.num} is {'a Happy' if next_num == 1 else 'an Unhappy'} number."
@staticmethod
def _getnext(num: int): # 숫자 -> 각 자리수 제곱의 합
return sum(int(c) ** 2 for c in str(num))
def main():
numcases = int(input())
cases = [int(input()) for _ in range(numcases)]
for i, v in enumerate(cases):
case = HappyNum(v)
print(f"Case #{i + 1}: {case.getstatstr()}")
if __name__ == "__main__":
main()
p = int(input('')); L = []
for i in range(p) :
L.append(input(''))
for N in range(len(L)):
tmp = int(L[N]); result = 0
while True :
for s in str(L[N]) :
result += int(s)**2
if result == 1 :
print('Case #%d: %d is a Happy number.' % (N+1, tmp))
break
elif result == tmp :
print('Case #%d: %d is an Unhappy number.' % (N+1, tmp))
break
L[N] = result
result = 0
python
p = int(input('숫자 리스트의 길이를 입력하세요> '))
num_list = list(map(int,input('p개의 양의 정수를 입력하세요> ').split()))
def happy(n):
num = n
while True:
sum = 0
for i in range(len(list(str(num)))):
sum += int(list(str(num))[i])**2
num = sum
if num == 1:
return str(n) + ' is a Happy number.'
break
if num == 4:
return str(n) + ' is an Unhappy number.'
break
for i in range(len(num_list)):
print('Case #' + str(i+1) + ': ' + happy(num_list[i]))
import java.util.*;
public class HappyNumber {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[] nums = new int[n];
for(int i=0; i<n; i++) {
nums[i]=scan.nextInt();
}
ArrayList<Integer> list = new ArrayList<Integer>();
String A = null;
for(int i=0; i<n; i++) {
int N = 0;
list.clear();
list.add(nums[i]);
N=nums[i];
outerLoop:
while(true) {
if(nums[i]*nums[i]!=nums[i]) {
A = Integer.toString(N);
String[] B = A.split("");
int a = 0;
for(int j=0; j<B.length; j++) {
a += Integer.parseInt(B[j])*Integer.parseInt(B[j]);
}
list.add(a);
N=a;
if(N==1) {
System.out.println("Case #"+(i+1)+": "+nums[i]+" is a Happy number.");
break;
}
else {
for(int k=0; k<list.size()-1; k++) {
if(a==list.get(k)) {
System.out.println("Case #"+(i+1)+": "+nums[i]+" is an Unhappy number.");
break outerLoop;
}
}
}
}
}
}
}
}
어떻게 풀었는지......
n=input("양의 정수 n을 입력하십시오: ")
fn=n #최종 출력을 위한 n을 할당
while True: #행복수 계산 과정
result=0
for num in n:
result+=int(num)**2
n=str(result)
#print(n) #행복수를 찾는 과정을 진행하다보면 행복수가 아닌 수들은 계산 과정에서
#37(또는 73),58(또는 85),89(또는 98),145,42(24는 안 나오는 것 같음),20,(경우에 따라 4나오기 전에 2),4가 나오는 과정이 반복됨.
if n=="1": #계산 결과가 1이면 행복수
print(fn, "is a Happy number")
break
elif n=="4": #따라서 행복수가 아닌 수들의 계산 과정에서 나오는 수들 중 1개가 나오면 break를 하고 그 수를 출력.(여기선 그냥 4라고 해봄.)
print(fn, "is a Unhappy number")
break
data = input("숫자 입력 : ")
Run = True
sum_list =[]
while Run:
sum = 0
for i in data:
sum = sum + int(i)**2
print(sum)
if sum == 1:
#print(sum)
print("Happy Number")
Run = False
else :
if sum in sum_list:
#print(sum)
print("Unhappy Number")
Run = False
else :
sum_list.append(sum)
data=str(sum)
#파이썬
def mulsum(x): # 입력받은 수의 각 자리수의 제곱의 합을 구해주는 함수
sum=0
for k in range(len(str(x))):
sum+=(int(str(x)[k]))**2
return sum
n=int(input('n='))
c=[]
for i in range (n):
a=int(input('case'+str(i)+': '))
if a>0 and a<10**9: # 1보다 크고 10^9인 경우에만 리스트에 추가시킴
c.append(a)
for i in range (len(c)):
c_list,a=[],c[i]
while (1):
c_list.append(a) #mulsum함수를 돌린 값을 리스트에 추가시킴
a=mulsum(a)
if a==1:
print ('Case #'+str(i)+': '+str(c[i])+' is a Happy Number')
break
if a in c_list: # mulsum 함수를 돌린값이 리스트에 이미 있으면 Unhappy
print ('Case #'+str(i)+': '+str(c[i])+' is a Unhappy Number')
break
import time
def happy(e):
k = [str(e)]
while k[len(k)-1] != '1' and not ((k[len(k)-1] in k[:len(k)-1]) and k.index(k[len(k)-1]) != 0):
s = 0
for i in k[len(k)-1]:
s += int(i) ** 2
k.append(str(s))
print('{} is a {}'.format(e, 'Happy Number' if k[len(k)-1] == '1' else 'Unhappy Number'))
if __name__ == '__main__':
t = time.time()
for x in range(1, 1000000):
happy(x)
print(time.time() - t)
def check_happy(n):
num_list = [n]
def add_squared(x):
return sum([int(i) ** 2 for i in str(x)])
while True:
next_num = add_squared(num_list[-1])
if next_num == 1:
return True
if next_num in num_list:
return False
num_list.append(next_num)
n =str(input())
happylist = [n,]
for i in happylist:
ilist = '0'
for k in range(0,len(i)):
ilist = str(int(ilist) + (int(i[k])**2))
print(ilist)
if ilist == '1':
print('happynumber')
elif len(happylist) > 1 and happylist[0] == happylist[-1]:
print("unhappy number")
break
else:
happylist.append(ilist)
print(happylist)
def happyNumber(n) :
mem = [n]
while True :
n = sum([int(i)**2 for i in list(str(n))])
if n == 1 : return print("%d is a happy number." %mem[0])
elif n in mem : return print("%d is an unhappy number." %mem[0])
else :
mem.append(n)
continue
if __name__ == "__main__" :
happyNumber(3)
happyNumber(44488)
happyNumber(44)
결과
3 is an unhappy number.
44488 is a happy number.
44 is a happy number.
def happyNumber(n):
number = ",".join(str(n)).split(",")
while 1:
result = 0
for i in range(0,len(number)):
result += int(number[i])**2
if result == 1:
print(str(n)+" is a Happy number")
break
elif result == n:
print(str(n) + " is a Unhappy number")
break
else:
number = ",".join(str(result)).split(",")
continue
happyNumber(7)
happyNumber(4)
happyNumber(13)
def happy_number(numbers):
for_answer=[numbers]
new_number=0
check=False
while check==False:
new_number=0
while numbers>0:
new_number+=(numbers%10)*(numbers%10)
numbers=numbers//10
if new_number in for_answer:
check=True
for_answer.append(new_number)
numbers=new_number
if new_number==1:
return 'a Happy Number'
break
return 'an Unhappy Number'
print('{} is {}'.format(3,happy_number(3)))
print('{} is {}'.format(7,happy_number(7)))
print('{} is {}'.format(13,happy_number(13)))
print('{} is {}'.format(4,happy_number(4)))
def Happynum():
n = int(input('number of input : '))
number_list = []
for i in range(n):
number_list.append(input('NUMBER : '))
count = 0
case = []
for member in number_list:
while True:
if count == 0:
case.append(member)
sum = 0
for aa in case[-1]:
sum += int(aa)**2
# print(aa, sum)
if sum == 1:
print('Case {} : {} is a Happy number'.format(3-n, member))
case.append(str(sum))
# print(case)
case = []
n = n - 1
count = 0
break
elif str(sum) in case:
print('Case {} : {} is an Unhappy number'.format(3-n, member))
case.append(str(sum))
# print(case)
case = []
n = n - 1
count = 0
break
else:
# print('APPENDED:', str(sum))
case.append(str(sum))
if count == 50 :
count = 0
break
count += 1
Happynum()
e=int(input("숫자를 입력하세요 : "))
a=0
w=0
a=e
c=[]
while True:
for j in range(len(str(e))):
w+=int(str(e)[j])**2
if 1 in c:
break
elif w in c:
break
else:
c.append(w)
e=0
e+=w
w=0
if 1 in c:
print("{} is a Happy Number".format(a))
else:
print("{} is a Unhappy Number".format(a))
case = int(input('sample count :'))
c = 0
while c<case:
n = int(input('sample:'))
c +=1
h= [0]
h.append(n)
while h[-1]>=1:
if h[-1] == h[-2]:
print(f'case #{c} {n} is an Unhappy number.')
break
elif h[-1]==1:
print(f'case #{c} {n} is a Happy number.')
break
else :
for i in str(h[-1]):
l=[]
l.append(int(i)**2)
s= sum(l)
h.append(s)
def happynum(n):
num = [n]
while n != 1 or n < pow(10,9):
k = 0
for i in str(n):
k += int(i)**2
n = k
num.append(k)
continue
return print(num)
def result(n):
if happynum(n).count(n) >= 2:
return print("Unhappy Number")
elif happynum(n).count(n) == 1: return print("Happy Number")
happynum(7)
result(n)
#codingdojing_happyNum_re
#각 자리의 수의 합.. 아무리 커봤자 99*자릿수 천을 넘어갈 일은 없다.
#데이터셋이 많다는 가정하에, 다른 방식으로 수정. 집합을 이용한다. happy를 분석하는 과정에서
# 판별하는 숫자가, happy나 unhappyset에 없다면, 그 숫자를 처음부터 끝까지 분석.
# 각 중간 숫자를 비교할 필요는 없을 듯, 어차피 몇 번 돌면 다 포함되어 있을텐데
# 처음 풀이는 틀렸다. 예를 들어, 2의 경우, 처음숫자가 아니라 다른 숫자들이 반복된다. set으로 비교해야 하겠네.
def happyNum(s):
return str(sum([int(i)**2 for i in s]))
n = eval(input('sample num: '))
happySet = set()
unhappySet = set()
currentSet = set()
for i in range(1, n+1):
s1 = str(i)
while True:
if s1 in happySet or s1 == '1': #최종값이 1이거나, 이미 셋에 포함되어 있기때문에 add안한다.
happySet.update(currentSet)
currentSet.clear()
print(f'Case #{i}: {i} is a happy number.')
break
elif s1 in unhappySet or s1 in currentSet: #최종값이 이미 현재 셋에 있거나, 언해피 셋에 있기 때문에 add 안해도 됨.
unhappySet.update(currentSet)
currentSet.clear()
print(f'Case #{i}: {i} is a unhappy number.')
break
else:
currentSet.add(s1) #검사한 숫자
s1 = happyNum(s1) #새로운 숫자
n = int(input("TEST CASE 수는?"))
num_arr =[]
for i in range(n):
while True :
print(i+1,"번째")
a = int(input("검증할 숫자는?"))
if a>=0 and a<10**9 :
num_arr.append(a)
break
def Solution(n) :
a = n
arr =[]
while True :
sum =0
b = list(map(int,str(a)))
for k in b :
sum += k**2
if sum in arr:
break
arr.append(sum)
a = sum
if 1 in arr:
print(n,"is a Happy number")
else :
print(n,"is an Unhappy number")
for k in num_arr :
Solution(k)
// Rust
// happy인지 unhappy인지 결과가 나오면 바로 결과를 return합니다
// 중간 계산 값들을 map에 넣을지 고민입니다
use std::collections::HashMap; fn happy_number(n: usize) -> bool {
let mut map: HashMap<usize, bool> = HashMap::new();
let mut vec = vec![n];
loop {
let mut d = vec[vec.len()-1];
let mut sum = 0;
while d > 0 {
sum += (d % 10).pow(2);
d /= 10;
}
if sum == 1 {
return true;
}
if vec.contains(&sum) {
return false;
}
vec.push(sum);
}
}
fn test() {
assert_eq!(happy_number(7), true);
assert_eq!(happy_number(4), false);
assert_eq!(happy_number(13), true);
assert_eq!(happy_number(0), false);
}
a = '''3
7
4
13'''
sam_list =list(map(int,a.split('\n\n')))
sam_num = sam_list[0]
def happy_seq(n):
seq = []
seq.append(n)
jud = sum([int(x)**2 for x in str(n)])
while jud not in seq:
seq.append(jud)
jud = sum([int(x)**2 for x in str(seq[-1])])
if min(seq) == 1: return 'is a Happy number.'
else: return 'is an Unhappy number.'
for i in range(sam_num):
print(f'{sam_list[i+1]} {happy_seq(sam_list[i+1])}')
for n in range(1,100000):
S = sum([int(i)*int(i) for i in str(n)])
Slist = [n]
while S != 1 and S not in Slist:
Slist.append(S)
S = sum([int(i)*int(i) for i in str(S)])
if S == 1:
count += 1
print(f"Case #{n}: {n} is a Happy number.")
else:
print(f"Case #{n}: {n} is a Unhappy number.")
// javascript 입니다. // 고수님들 제 풀이 평가 부탁드립니다 ~.~
const solution = (num) => {
// 캐시에 값을 담고 캐시의 값과 일치한다면 종료 후 판별하여 리턴
const cache = [];
let result = 0;
while(result !== 1){
result = String(result===0?num:result).split('').map(i=>parseInt(i**2)).reduce((a,b) => (a+b));
if(cache.some(i=> i===result)){
break;
}
cache.push(result);
}
if(result===1){
return `${num} is a Happy Number`;
}else{
return `${num} is an Unhappy Number`;
}
}
def isHappyNumber(N, lst):
nextN = 0
while N > 0:
nextN += (N % 10)**2
N //= 10
if nextN == 1:
return True
elif nextN in lst:
return False
else:
lst.append(nextN)
return isHappyNumber(nextN, lst)
n = int(input('인풋 케이스의 수: '))
inputN = []
for i in range(n):
inputN.append(int(input('{}번째 양의 정수는: '.format(i+1))))
print(' =' * 10)
for i, N in enumerate(inputN):
if isHappyNumber(N, [N]):
print('Case #{0}: {1} is a Happy number'.format(i+1, N))
else:
print('Case #{0}: {1} is an Unhappy number'.format(i+1, N))