이 페이지는 코딩도장 데이터의 읽기 전용 정적 보관본입니다.

제곱 사이클

  • 입력으로 어떤 수가 주어집니다. (예시: 12)
  • 이 수의 각 자릿수의 제곱을 각각 구합니다. (예시: 1, 4)
  • 이 수들을 모두 더합니다. (예시: 5)
  • 한 자리 수가 나오면 그냥 제곱만 하면 됩니다. (예시: 25)
  • 이것을 반복합니다. (예시: 12 - 5 - 25 - 29 ...)
  • 이때, 4처럼 순환하는 경우가 있습니다. (4 - 16 - 37 - 58 - 89 - 145 - 42 - 20 - 4 [무한 반복])
  • 여기에서 순환할 때 지나가는 수의 개수를 출력합니다. (4에서는 8개[4, 16, 37, 58, 89, 145, 42, 20])
  • 100번 계산해도 순환되는 것이 나오지 않으면 '100개 이상'을 출력합니다.

input

4

output

8
for

2021/06/26 11:24

이준우

35개의 풀이가 있습니다.

next = int(input('자연수:'))
nums = []
while (len(nums)<=100) and (next not in nums):
  nums.append(next)
  next = sum([int(c)**2 for c in str(next)])
print('100개 이상' if len(nums)>100 else len(nums))

2021/06/28 15:31

김준우

python 3.9.5입니다. sys.exit을 실행시키면 프로그램이 종료되는 것을 이용했습니다. 소스 코드입니다.

import sys

start_num = int(input('시작할 수를 입력하세요. '))
num = start_num

for i in range(1, 101):
    num_list = []
    for j in str(num):
        num_list.append(int(j) ** 2)
    num = sum(num_list)
    if num == start_num: print(i); sys.exit()

print('100회 이상')

실행 결과입니다.

시작할 수를 입력하세요. 4
8
시작할 수를 입력하세요. 12
100회 이상

2021/07/03 09:40

이준우

n = int(input('숫자를 입력하세요. : '))

list_num = [n]
num = n
uru = True

for i in range(1, 101) :
    hap = 0
    for nb in list(str(num)) : 
        hap += int(nb) ** 2

    if hap == n :
        uru = False
        break
    else :
        list_num.append(hap)
        num = hap    

if uru : 
  print('100개 이상')
else :
  print(len(list_num))

2021/07/07 14:12

최벽문

import java.util.ArrayList;
import java.util.Scanner;

public class SquaredCycle {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("처음 입력할 수 : ");
        String firstInput = scanner.next();

        // 입력한 문자를 숫자로 기억해주고, 각 자리 수의 제곱들의 합을 저장해주는 변수
        int changeInput = 0;
        // 첫번째 입력한 수를 기억해주는 변수
        int firstInputNum = Integer.parseInt(firstInput);
        // 순환횟수를 기억해주는 변수
        int cntCycle = 0;

        ArrayList<Integer> arSqarededCycle = new ArrayList<Integer>();

        while (true) {
            for (int i = 0; i < firstInput.length(); i++) {
                changeInput += Math.pow(Integer.parseInt(""+(firstInput.charAt(i))), 2);
            }
            cntCycle ++;
            arSqarededCycle.add(changeInput);

            if(firstInputNum==changeInput) {
                System.out.println(arSqarededCycle.size()+"개 " + arSqarededCycle);
                break;
            }else if(cntCycle>100) {
                System.out.println("100번 반복 넘음");
                break;
            }
            firstInput = ""+ changeInput;
            changeInput = 0;
        }
    }
}

2021/07/08 16:42

이원희

def square_cycle(num):
    num=str(num)
    if len(num)>1:
        i=0
        temp=0
        while (i<len(num)):
            temp+=(int(num[i])**2)            
            i+=1
    else:
        temp=int(num)**2

    return temp


num=int(input('숫자를 입력해주세요...'))
num2=num
for i in range (1,101):
    num2=square_cycle(num2)
    if num==num2:
        print (i)
        break


if i==100:
    print ('100번 이상')

2021/07/12 01:45

Buckshot

숫자를 입력해주세요...1 1 숫자를 입력해주세요...2 100번 이상 숫자를 입력해주세요...3 100번 이상 숫자를 입력해주세요...4 8 숫자를 입력해주세요...77 100번 이상 - Buckshot, 2021/07/12 01:46

package justStudying;

import java.util.HashMap;

public class test2_20210806 {

public static int count = -1;

public static void req(String num, HashMap<Integer, Integer> m, int count) {
    int sum = 0;

    if(count >= 100) {
        test2_20210806.count = count;
        return;
    }

    int t = 0;
    for(int i=0; i<num.length(); i++) {
        t = Integer.parseInt(num.substring(i, i+1));
        sum +=  (t*t);
    }

    count++;
    System.out.println(num+ " => [" + sum + "] " + count + "번째");

    if(m.get(sum) != null) {
        test2_20210806.count = count;
        return;
    }
    else {
        m.put(sum,sum);
        req(Integer.toString(sum), m, count);
    }


}


public static void main(String[] args) {
    // TODO Auto-generated method stub
    HashMap<Integer,Integer> a = new HashMap<Integer,Integer>();
    a.put(4,4);
    req("4", a, 0);

    System.out.println(count);
}

}

2021/08/06 20:54

이병호

user=int(input())
cycle=0
save=user
while cycle<100:
    add = 0
    i=str(save)
    for j in range(len(str(save))):
        add+=int(i[j])**2
    cycle+=1
    if add==user:
        print(cycle)
        break
    save=add
if cycle>=100:
    print('100개 이상')

2021/08/08 23:36

Percy

N = int(input("입력 : "))
EN = []
while True:
    EN.append(N)
    N = sum([int(a)**2 for a in str(N)])
    if N in EN: break
    if len(EN) >= 100: print("100개 이상"); break
print(len(EN))

2021/08/09 04:50

[w]*눈꽃*

def check(N):
    return sum(list(int(i)**2 for i in N)) if (len(N) > 1) else int(N)**2
N = input()
agg_N = int(N)
for i in range(100):
    N = check(str(N))
    if (agg_N == N):
        print(i+1)
        break
if (agg_N != N):
    print("100개 이상")

2021/08/16 16:00

BlakeLee

Python 3

def sqr_seq(arg: int):
    src = [arg] # 제곱사이클 수열
    hasfound = False # 제곱사이클 종료 조건
    while len(src) < 100:
        chkval = src[-1]
        nextval = sum(int(s) ** 2 for s in str(chkval))
        if nextval in src:
            hasfound = True # 순환을 찾은 경우
            break
        src.append(nextval)
    return hasfound, src


if __name__ == '__main__':
    arg = 12
    rst = sqr_seq(arg)
    expr = str(len(rst[1])) if rst[0] == True else "100개 이상"
    print(expr)

2021/08/19 11:29

mohenjo

number = input()
number_init = number

i = 0
while i < 101:
    i += 1
    sum_number = 0
    for x in str(number):
        sum_number += int(x)**2
    number = sum_number
    print(sum_number)
    if number == int(number_init):
        break

if i >= 100:
    i = "100개 이상"
print(i)

2021/08/26 16:32

코딩버거

inp=int(input('숫자를 입력하십시오: '))
clone=inp
sum=0
loop=0


while 1:
    while inp!=0:
        num=int(inp%10)
        inp=inp/10
        sum+=num**2
    inp=sum
    sum=0
    loop+=1
    if loop==100:
        print('100개 이상')
        break
    elif inp==clone:
        print('{0}에서는 {1}개'.format(clone, loop))
        break


2021/08/27 22:50

Jun Young Park

a = input("숫자입력: ")
c = 0
ori = int(a)
count = 0
while True:
    b = []
    for i in a:
        b.append(int(i)**2)
    c = 0
    for i in b:
        c += i
    count += 1
    if count == 100:
        print("100 이상")
        break
    elif c == ori:
        print(count)
        break
    else:
        a = str(c)

2021/09/08 11:20

한고선

def sol() : 
    result = [input("INPUT : ")]
    for i in range(0, 100) :
        result.append(str(sum(map(lambda x : int(x)**2, list(result[-1])))))
        if result[:int(len(result)/2)] == result[int(len(result)/2):] : 
            return int(len(result)/2)
    return "100개 이상"

if __name__ == "__main__" :
    print(sol())

파이썬입니다.

2021/09/14 12:13

GG

void main()
{   

    char Input[10];
    cin >> Input;   
    vector<int> eachNums;
    int LoopCnt = 1;

    string pattern;
    int FirstInput = atoi(Input);
    string progress;

    pattern += Input;
    progress += Input;

    while (true)
    {
        int sum = 0;
        eachNums.clear();
        for (int i = 0; i < strlen(Input); i++)
        {
            eachNums.push_back(Input[i] - '0');
            sum += eachNums[i] * eachNums[i];
        }
        sprintf_s(Input, "%d", sum);
        progress += string(Input);
        pattern += string(Input);

        if (LoopCnt >= 100 || (sum == FirstInput && progress == pattern))
            break;

        if (sum < 10) sum *= sum;
        LoopCnt++;
    }

    cout << LoopCnt;

}

2021/10/07 12:01

aozora18

문제에서 '순환'을 만족하는 조건이 애매하네요. 예를 들어 초기값이 4면 결과는 4, 16, 37, 58, 89, 145, 42, 20, 4 ... 로 순환하지만 초기값이 2면 결과는 2, 4, 16, 37, 58, 89, 145, 42, 20, 4 ... 로 마찬가지로 순환하나 순환 시작 지점이 중간에 있습니다. 이러한 경우도 순환하는 것으로 취급할지 여부를 문제에서는 명확히 알 수 없네요.

일단 두 경우 모두 작성해 보았습니다.

1) 순환 시작 지점은 맨 앞만 허용

def pow_cycle(n):
    lis=[n]
    while lis.count(lis[0])==1 and len(lis)<100:
        lis.append(sum([int(i)**2 for i in str(lis[-1])]))
    print(f"{len(lis)-1}개") if len(lis)<100 else print("100개 이상")

2) 순환 시작 지점이 중간에 있어도 순환하는 것으로 취급

def pow_cycle(n):
    lis=[n]
    while lis.count(lis[-1])==1 and len(lis)<100:
        lis.append(sum([int(i)**2 for i in str(lis[-1])]))
    print(f"{len(lis)-1}개") if len(lis)<100 else print("100개 이상")

2021/10/11 21:45

LSW

num = input()   # 입력값
original = num
num_list = []   # 제곱사이클을 판단하기 위한 리스트
count = 0       # 사이클의 횟수
while True:
    count+=1
    if count>100:
        print("100개 이상")
        break
    elif original in num_list:
        print(count-1)
        break
    if len(num)==1:
        num_list.append(str(int(num)**2))
        num = str(int(num)**2)
    else:
        sum = 0
        for i in range(len(num)):
            sum+=(int(num[i])**2)
        num = str(sum)
        num_list.append(str(sum))


#print(num_list)

2021/10/25 14:40

fox.j

c입니다.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>


int get_length(char *input);
int inspect(int* arr, int value);

int main(void)
{
    char input[10];
    char buf[200];
    int length, cnt = 1;
    int result, i, flg;
    int arr[200];

    scanf("%s", &input);
    length = get_length(input);
    arr[0] = atoi(input);

    while (cnt <= 100)
    {
        result = 0;
        for (i = 0; i < length; i++)
        {
            result += pow((int)(input[i] - 48), 2);
        }
        int idx = inspect(arr, result);
        if (idx != 0)
        {
            printf("%d개", cnt - idx);
            flg = 1;
            break;
        }
        strcpy(input, _itoa(result, buf, 10));
        length = get_length(input);

        arr[cnt] = result;
        cnt += 1;
    }
    if (flg == 0)
    {
        printf("100번 이상");
    }

    return 0;
}

int get_length(char *input)
{
    int length = 0, i;
    for (i = 0; i < 10; i++)
    {
        if (input[i] == '\0')
        {
            break;
        }
        length += 1;
    }
    return length;
}

int inspect(int* arr, int value)
{
    int length = 100;
    for (int i = 0; i < length; i++)
    {
        if (arr[i] == value)
        {
            return i;
        }
    }
    return 0;
}

2021/12/02 01:23

형제는못말려

a= int(input("제곱 사이클 검증 수 입력"))


def convert(a):
    arr = list(map(int,str(a)))
    result = 0
    for i in arr:
        result += i**2
    return result

arr = [a]
n=1
while True:
    result = convert(a)
    if n ==100:
        print("100개 이상")
        break
    else:
        if result not in arr:
            n+=1
            arr.append(result)
            a = result
        else:
            print(n-arr.index(result))
            break

print(arr)

문제설명이 조금 부족한데, 제가 이해하기로는 4로 시작해도 순환되는 LIST가 나오면 그떄의 순환되는 숫자들의 수를 출력 하도록 짜봤습니다. ex)12로 시작하면, [12, 5, 25, 29, 85, 89, 145, 42, 20, 4, 16, 37, 58, 145. . .. . . . . . 12는 순환이 안돼지만 [145, 42, 20, 4, 16, 37, 58, 145. . ] 가 반복 되어 순환되는 숫자들의 수인 '8'이 출력 되도록 함

2022/01/31 01:22

양캠부부

파이썬입니다.


n = int(input())
a = {n}
while len(a) < 100:
    s = 0
    while n:
        n, m = divmod(n, 10)
        s += m ** 2
    n = s
    if n in a:
        print(len(a))
        break
    a.add(n)
else:
    print('over 100')

2022/02/07 11:55

룰루랄라

// Rust

// successors 이터레이터, .find 및 Option::map 메써드를 사용하였습니다

fn sum_square_cycle() {

let input = 4;
let limit = 100;

let cycle_num = std::iter::successors(Some(input), |&n| {
    if n < 10 { Some(n * n) }
    else {  let n_ = n.to_string();
            Some(n_.chars()
                    .map(|c| {  let c_ = c.to_digit(10).unwrap();
                                c_ * c_})
                    .sum())
    }})
    .skip(1)
    .take(limit - 1)
    .enumerate()
    .find(|(_, n)| *n == input)
    .map(|(i,_)| i);

match cycle_num {
    Some(n) => println!("{}", n + 1),
    None => println!("100개 이상"),
}

}

2022/02/08 19:44

JW KIM

n=4
sq_list = [n]

def ss(n):
    return sum([int(x)**2 for x in str(n)])

def add_list(n):
    if ss(n) < 10:
        return ss(n)**2
    else:
        return ss(n)

def sq_cyc(n):
    while add_list(n) not in sq_list:
        sq_list.append(add_list(n))
        n = add_list(n)
    if len(sq_list)>100:
        return '100개 이상'
    else:
        return len(sq_list)

sq_cyc(n)

2022/02/22 13:38

로만가

package org.javaturotials.ex;
import java.util.*;
import java.util.stream.Collectors;

public class test {
    public static void main(String[] args) {    
        Scanner sc =new Scanner(System.in);
        int num= sc.nextInt();
        int rnum = num;
        int count = 0;
        while(true) {
            int sum=0;
            String nums = String.valueOf(num);
            String[] arr =nums.split("");
            for(int i=0; i<arr.length; i++) {
                int t = Integer.valueOf(arr[i]);
                sum+= (t*t);
            }
            count++;
            num=sum;
            if(sum==rnum) break;
        }
        if(count>=100) {
            System.out.println("100개 이상");
        }
        else {
            System.out.println(count);
        }
    }
    }

2022/02/22 14:00

Kkubuck

n=int(input("#"))
li=[]
count=0
while True:
    sum = 0
    count+=1
    li.append(str(n))
    print(li)
    for i in str(n):
        sum+=int(i)**2
        print(sum)
    n=sum
    if str(n) in li:
        ban=0
        for i in li:
            ban+=1
            if i==str(n):
                print(f"{len(li)-ban}개 반복")
        break
    if count==100:
        print("100 개 이상")
        break

2022/05/10 16:00

yunjae

자바로 풀어봤습니다.

import java.util.Scanner;

public class test {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        System.out.println("자연수 N을 입력하시오:");
        int N = scan.nextInt();
        int count=0, copy=N, sum=0, storage;


        do {
            // count 증가
            count++;

            // 각 자리수 분리 후, 제곱 & 총합
            while(copy>0) {
                storage=copy%10;
                sum = sum+(int)Math.pow(storage,2);
                copy/=10;
            }

            copy=sum;

            // count가 100번 이상이면 break
            if(count==100) {
                break;
            }

            sum=0;
        }while(copy!=N);

        if(count==100) {
            System.out.println("100번 이상");

        }else {
            System.out.printf("%d번",count);
        }

    }
}

2022/06/09 13:39

유로

def squared_cycle(num):
    matrix, square_plus= [int(num)], 0
    while len(matrix) < 100:
        for i in num:
            square_plus += int(i)**2
        if matrix.count(square_plus) != 0: break
        matrix = matrix+[square_plus]
        num, square_plus = str(matrix[-1]), 0
    return len(matrix)

num = input('제곱 사이클을 확인하는 함수 입니다. \n자연수를 입력해주세요 : ')
result = squared_cycle(num)
print(f'{result}개 이상' if result > 100 else f'{result}개 반복')

2022/09/12 16:55

고양이

import java.util.Scanner;

public class Q2 {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String scan1 = scan.next();
        String backupscan = scan1;
        int count=0;
        while(true) {
            count++;
            int sum=0;
            int numcount = scan1.length();
            int[] input = new int[numcount];
            for(int i=0;i<numcount;i++) {
                input[i]=scan1.charAt(i)-'0';
            }
            for(int i=0;i<numcount;i++) {
                sum=sum+input[i]*input[i];
            }
            if(Integer.parseInt(backupscan)==sum) {
                System.out.println(count);
                break;
            }
            if(count>=100) {
                System.out.println("100개 이상");
                break;
            }
            scan1=Integer.toString(sum);
        }
    }

}

2022/09/21 09:20

김민중

def squareCycle(number):
    res = 0
    cnt = 0
    num = str(number)
    while res != int(number) and cnt <100:        
        res = 0
        cnt +=1
        for i in range(len(num)):
            n = int(num[i])
            #print(f'n => {n}')
            res += n *n

        num = str(res)
        print(num)

    if cnt < 100:
        print(cnt)
    else:
        print("100개 이상")

squareCycle(12)

2023/02/07 14:01

최종오

재귀호출

def re_squ(num, cycle_list):
    if len(cycle_list) == 100:
        print('100초과')
        return 0

    num_list = []
    for i in num:
        num_list.append(i)

    res_list = []
    for i in num_list:
        int_num = int(i)
        re = int_num * int_num
        res_list.append(re)

    result = str(sum(res_list))

    if result == cycle_list[0]:
        return 1
    else:
        cycle_list.append(result)
        re_squ(result, cycle_list)

#__main__
cycle_list = []
input_num = input("숫자 입력 : ")
cycle_list.append(input_num)
re_squ(input_num, cycle_list)

if len(cycle_list) != 100:
    print(cycle_list)

반복문

input_num = ''
num_list  = []
cycle_list = []

input_num = input("숫자 입력 : ")
cycle_list.append(input_num)
for i in input_num:
    num_list.append(i)

while_range = 0
result_val = ''
while(1):
    if while_range == 100:
        print("100이상")
        break
    n_list = []

    for i in num_list:
        int_val = int(i)
        squ_val = int_val * int_val
        n_list.append(squ_val)

    result_val = str(sum(n_list))
    if result_val == cycle_list[0]:
        break
    else:
        cycle_list.append(result_val)
        num_list.clear()
        for i in result_val:
            num_list.append(i)

    while_range += 1

if while_range != 100:
    print(cycle_list)

2023/03/31 14:02

HoHyeon Kim

using System;
using System.Collections.Generic;

namespace solution
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("\n 숫자를 입력하세요: ");
            int input = int.Parse(Console.ReadLine());

            Console.WriteLine("\n 순환할 때 지나가는 수의 개수: {0}", numOfSquareCycle(input));
        }

        private static string numOfSquareCycle(int input)
        {
            List<int> listNum = new List<int>();
            listNum.Add(input);
            int cnt = 0;
            int curr = 0;
            int tmp = 0;
            while (cnt < 100)
            {
                while (input > 0)
                {
                    tmp = input % 10;
                    input /= 10;
                    curr += tmp * tmp;
                }
                if (listNum.Contains(curr))
                    break;
                else
                {
                    listNum.Add(curr);
                    input = curr;
                    curr = 0;
                }
                cnt++;
            }
            return cnt == 100 ? "100개 이상" : listNum.Count.ToString();
        }
    }
}

2023/06/20 12:29

insperChoi

input_number = int(input("Enter Number:"))
num_list = list(map(int,str(input_number)))
sqr_list = []
sqr_sum = 0
count = 0
while input_number != sqr_number:
   count += 1
   for i in range(lne(num_list)):
      sqr_list.insert(i,(num_list[i]**2))
   sqr_sum = sum(sqr_list)
   sqr_list.clear()
   num_list.clear()
   num_list = list(map(int,str(sqr_sum)))
   if count > 100:
      print("Over 100 Times")
      break
   countinue
print(count,"Tries")

2023/07/11 11:46

siu yoon

num_list = []
l = [int(i) for i in input("Number=")]
while True:
  num = 0
  for i in l:
    num+=i**2
  if num not in num_list:
    if len(num_list) == 100:
      print("100개 이상")
      break        
    else: 
      num_list.append(num)
      l = [int(i) for i in str(num)]
  elif num in num_list:
    print(len(num_list))
    break 

2023/07/17 08:58

스탠리

n = input()
nLst = list(map(int, n))
cnt = 1

def pow(nLst):
    nPowSum = 0
    for i in nLst:
        nPowSum += i**2
    return nPowSum

nPowSum = pow(nLst)

while cnt <= 100:
    nLst2 = list(map(int, str(nPowSum)))
    if cnt == 100:
        print('Over 100')
        break
    elif pow(nLst) == pow(nLst2):
        print(cnt)
        break
    else:
        cnt += 1
        nPowSum = pow(nLst2)

2023/07/20 08:18

Hawk Lee

temp_num=str(input("숫자 입력"))
nums =[]
while True: 
    new_num=0
    for i in temp_num:
        new_num+= (int(i) **2)
    if new_num in nums:
        print(nums[nums.index(new_num):], str(len(nums[nums.index(new_num):]))+"개") #전체 갯수가 아닌 순환하는 숫자와 그 갯수를 출력
        break
    elif len(nums) >= 100:
        print("100개 이상")
        break
    nums.append(new_num)
    temp_num = str(new_num)

2023/08/14 12:27

JGCO

def squarecyc(a):
  b =list(str(a))
  sumb = sum(int(x)**2 for x in b)
  return sumb

temp = int(input("숫자 입력: "))
nums = []

while (len(nums) <= 100) and (temp not in nums):
  nums.append(temp)
  temp = squarecyc(temp) 

print("100 이상" if len(nums) == 100 else len(nums))

2025/02/25 15:05

Dasol Lee

목록으로