2나 5로 나눌 수 없는 0 이상 10,000 이하의 정수 n이 주어졌는데, n의 배수 중에는 10진수로 표기했을 때 모든 자리 숫자가 1인 것이 있다. 그러한 n의 배수 중에서 가장 작은 것은 몇 자리 수일까?
Sample Input
3
7
9901
Sample Output
3
6
12
156개의 풀이가 있습니다.
재귀함수로 짜봤어요 결과는 바로바로 나오네요
def One (n,m=1,k=0,l=0):
k += m % n
l += 1
if k%n == 0: print(l)
else:One(n,m*10,k,l)
One(3)
One(7)
One(9997)
Algorithm:
(N=1부터 시작해서, 1씩 증가시킴)
입력된 수를 1로만 구성된 N개 자리의 수로 나누는 걸, 나누어질 때까지 반복합니다
package h_Ones;
import java.util.Scanner;
public class Ones {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int L=30;//입력값 수 제한
int l,i,j,N; long n;
long input[]=new long[L];
System.out.println("To stop inputting, input 0.");
for(l=0;l<L;l++){ input[l]=in.nextLong(); if(input[l]==0) break;} //입력
for(i=0;i<l;i++){
/*Algorithm*/
N=-1;
do{
N++;
n=1; for(j=1;j<N;j++) n=n*10+1; //n= 1로만 이루어진 N자리의 수
}while(n%input[i]!=0);
System.out.print(N+" ");
/*Algorithm ends*/
} System.out.println(" end. l:"+l);
}}
# 입출력예시
To stop inputting, input 0.
3 7 9901 21 53 47 91 1 111 31 0
3 6 12 6 13 58 6 0 3 15 end. l:10
파이썬입니다.
배수 증가시키는 부분은 좀 더 개선할 수 있을 것 같습니다. "1"로 이루어진 숫자인지 체크하는 함수는 파이썬 딕셔너리를 이용하여 한번에 찾을 수 있도록 해 봤습니다. 그래도 9901 같은 경우는 4초가량 걸리네요.
import unittest
chk_num = {}
for i in range(1,100): chk_num[int("1"*i)] = ""
def isOne(n):
if n in chk_num: return True
return False
def checkOne(no):
i = 1
while True:
n = no * i
if isOne(n): return len(str(n))
i += 1
class MyTest(unittest.TestCase):
def test1(self):
self.assertEquals(3, checkOne(3))
self.assertEquals(6, checkOne(7))
self.assertEquals(12, checkOne(9901))
if __name__ == "__main__":
unittest.main()
배수증가 시키는 부분을 Katherine 님의 알고리즘으로 변경 해 봤습니다. 훨씬 쾌적하네요 ㅋ
import unittest
chk_num = [int("1"*i) for i in range(1,1000)]
def checkOne(no):
for c in chk_num:
if c % no == 0:
return len(str(c))
class MyTest(unittest.TestCase):
def test1(self):
self.assertEquals(3, checkOne(3))
self.assertEquals(6, checkOne(7))
self.assertEquals(12, checkOne(9901))
self.assertEquals(192, checkOne(9997))
self.assertEquals(36, checkOne(9999))
if __name__ == "__main__":
unittest.main()
파이썬으로 해보았습니다. 입력된 수에 계속 1식 증가한값을 곱하다가 1이나 11,111,1111,11111....등의 수를 만나면 출력하는 방식으로 해보았네요(완전 초보라 어렵네요)
def Chknum(a):
j = 0
n = 1
powSize = 0
incSize = 1
m = 0
while j != n:
nd = len(str(a))
n = int(str(1)*nd)
j = a * m
m += 1
if n < j :
powSize += 1
incSize = 10**(powSize+nd-1)
n += incSize
print len(str(n))
파이썬으로 한번 만들어보았습니다. 어떻게하면 더 효율적일지 계속 고민하게되네요.
#
# Return the digit satisfying the given condition
#
def cat_dig(number):
mul_int = number
result = False
while result == False:
digit = len(str(mul_int))
if mul_int == int('1' * digit) :
result = True
else : result = False
mul_int += number
return digit
#
# -------------------------------------------------------
# Check the input is correct
#
while True:
while True:
try :
integer = int(input('Input an positive integer not multiple of 2 or 5 and smaller than 10,000 : '))
break
except (TypeError, ValueError) : print("You have to input an ineger")
if integer >= 10000 or integer <= 0:
print("This is not a positive integer or is too large")
elif divmod(integer, 2)[1] == 0 or divmod(integer, 5)[1] == 0:
print("It is divisible by 2 or 5")
else :
break
#
# Run cat_dig(integer) and print the result
#
print(cat_dig(integer))
파이썬으로 만들어보았습니다. 나머지 연산을 이용해 자리수 1을 조사하구요 for문에서 짝수배는 11..1같은 수가 나올 수 없으므로 홀수배만 조사하였습니다. 숫자를 입력받을때 짝수이면 바로 없다고 출력하거나 for문에서 5의 배수일 경우 continue시키면 조금 더 빨라질 수도 있을 것 같습니다.
# -*- coding: euc-kr -*-
input_number = input("Input a odd integer between 0 and 10000 : ")
number = int(input_number)
Max_Multiplier = 100000000
for i in range(1, Max_Multiplier + 1, 2):
check_number = number * i
number_len = len(str(check_number))
check_answer = 0
for j in range(1, number_len + 1):
if((check_number % pow(10, j)) == 1 * pow(10, j - 1)):
check_number -= pow(10, j-1)
if(j == number_len):
print(number_len)
check_answer = 1
break
else:
break
if(check_answer == 1):
break
if(check_answer == 0):
print("%d 배수 내에 해당 숫자가 없습니다" % Max_Multiplier)
Ruby
1을 하나씩 늘려가며 해당하는 수의 배수인지 판정합니다.
def ones(target)
return 0 if target % 2 == 0 or target % 5 == 0
1.upto(Float::INFINITY).lazy.each {|i| return i if ("1"*i).to_i % target == 0}
end
Test
assert_equal ones(2), 0
assert_equal ones(3), 3
aasert_equal ones(9997), 192
파이썬입니다. 재귀함수를 사용했습니다.
def ones(n,allones=0):
allones = allones * 10 + 1
if allones % n == 0:
print("input = %s result = %s" % (n,len(str(allones))))
else:
ones(n,allones)
ones(3)
ones(7)
ones(9901)
ones(1)
ones(9997)
ones(9999)
test 내용은 아래와 같습니다.
input = 3 result = 3
input = 7 result = 6
input = 9901 result = 12
input = 1 result = 1
input = 9997 result = 192
input = 9999 result = 36
포트란입니다. Starleaguer님의 풀이방법을 따라했습니다. mod 부분은 빠른 계산을 위해 Modular exponentiation 을 사용했습니다.
program codingdojo431
implicit none
integer i, j, n, m, sum
parameter (m=10)
!------------------
read *,i
j=0
do while(.TRUE.)
sum=0
do n=0, j
if(n .EQ. 0) then
sum=sum+1
else
sum=sum+modular_pow(m, n, i)
end if
end do
if(mod(sum, i) .EQ. 0) then
print *,j+1
exit
end if
j=j+1
end do
read *,i
!Modular exponentiation
contains
integer function modular_pow(base, exponent, modulus)
integer base, exponent, modulus, e_prime
!------------------
modular_pow = 1
do e_prime = 1, exponent
modular_pow = mod((modular_pow * base), modulus)
end do
return
end function
end program
파이썬 이제 막 시작하는 초보로써 책만 보고 하니 재미도 없고 해서 시작해봅니다. 제일 낮은 난이도 인거 같은데 문제만 이해하는데도 오래걸렸네요 ㅋㅋ
아주 단순하게 10으로 나눠서 나머지 값을 계속 확인해봤는데 어마어마하게 오래걸리네요 ㅋㅋ
좀 더 빠르게 할 수 있을텐데... 윗 분들 알고리즘 보고 배워야겠네요
def One(n):
if n%2==0 or n%5==0 :
print('input number is wrong.')
i=0
while True :
i = i+1
if i%2==0 or i%5==0 :
continue
result = checkOne(n*i, 0)
if result > 0 :
print result
break
def checkOne(n, depth):
if n%10 == 1 :
depth = depth + 1
if n >= 10 :
return checkOne(n/10, depth)
else :
return depth
else :
return 0
if __name__ == '__main__':
One(3)
One(7)
One(9901)
php 입니다. 아직은 할 줄 아는 게 이것 뿐이라서요;
그리고 여기 처음입니다. 가입인사(?) 드려요~ :)
/**
* $n : 입력할 수
* $i : 10의 배수 및 자릿수 체크
* $k : % 로 나눌 값
*/
function one($n, $i=1, $k=1) {
$k += pow(10, $i); /* 10의 $i 승 */
$i++;
if( ($k % $n) === 0)
echo $i;
else
one($n, $i, $k);
}
입력한 수로 1, 11, 111, 1111 ... 을 계속해서 나누도록 했습니다. 값이 바로 나오긴 하네요.
public class Ones {
public static long ones( int number ) {
int value = 1;
int n = 1;
int numberOfOne = 1;
while( n % number != 0) {
value *= 10;
n += value % number;
++numberOfOne;
}
return numberOfOne;
}
public static void main(String[] args) {
System.out.println(ones(7));
}
}
파이썬 3.2.5 기준입니다.
while True:
sample = int(input("2나 5로 나눌 수 없는 정수를 입력하세요 : "))
if sample % 2 == 0 or sample % 5 == 0:
print('{}는 2나 5로 나눌 수 있습니다.'.format(sample))
else: break
i = 1
while True:
if i % sample == 0:
print(len(str(i)))
break
i = int(str(i) + '1')
1 #/usr/bin/evn python
2
3 def ones(num):
4 out = '1' #시작은 1부터
5 str = int(out) #integer를 string으로 변환
6 temp = 1 #총 1의 개수. => 시작은 1개부터니까 1
7
8 while(1):
9 if ( str % num ) == 0 : #나눠 떨어지면 정답
10 return temp #1의 개수를 리턴
11 else :
12 out = out + '1' # 나눠 떨어지지 않았다면 1을 증가
13 str = int(out)
14 temp = temp + 1 # 1의 개수를 가지고 있는 temp값도 1 증가,
15 # temp는 integer이다.
16
17 print ones(3)
18 print ones(7)
19 print ones(9901)
형변환 때문에 약간 애를 먹었네요..파이썬을 시작한지 얼마 안되서..
[설명]
[실행결과]
3
6
12
Java로 작성하였습니다.
import java.util.Scanner;
public class Ones {
public static void main(String[] args) {
String input;
Scanner scan = new Scanner(System.in);
System.out.print("input number");
input = scan.nextLine();
System.out.print(check(Long.parseLong(input)));
}
public static int check(long input) {
int i = 0;
int j = 1;
long k = input;
while(k!=0) {
if(k%10 == 1) {
k = (k-1)/10;
i++;
}
else {
i = 0;
j++;
k = input * j;
}
}
return i;
}
}
2.
import java.util.Scanner;
public class Ones2 {
public static void main(String[] args) {
String input;
Scanner scan = new Scanner(System.in);
System.out.print("input number");
input = scan.nextLine();
System.out.print(check(Long.parseLong(input)));
}
public static int check(long input) {
int i = 1;
for(i = 1 ; ; i++)
{
if(makeOne(i) % input == 0)
break;
}
return i;
}
public static long makeOne(int input) {
long result=0;
for(int i = 0 ; i<input ; i++)
result += Math.pow(10, i);
return result;
}
}
/ 두가지 방식으로 작성해보았습니다. 첫번째는 input을 계속 곱해나가면서 10으로 나눌시 1의 나머지가 계속해서 생기는지 확인하는 방식이고 두번째는 반대로 1, 11, 111 순으로 나열해나가면서 각 수가 input의 배수인지 확인하는 방식입니다. /
def ones(num):
if num % 2 == 0 or num % 5 == 0:
print("input is a multiple of 2 or 5"); return
elif num < 0 or num > 10000:
print("out of range"); return
else:
cnt = 0
while 1:
cnt += 1
if int('1'*cnt) % num == 0:
return cnt
if __name__ == "__main__":
print(ones2(9991))
//swift 코드로 작성하였습니다.
//2나5로나눌수없는 0이상 10000이하의 정수 입력
//10진수로 표시했을때, 모든 자리 숫자가 1인 숫자가 있다.
//입력한 정수의 배수 중에서 가장 작은 것(111,1111,11111)은 몇자리 수 일까?
func fnOnes(input:Int)-> String{
if( input < 0 || input > 10000){
return "0이상 10000이하의정수만 가능합니다.";
}
if( input%2 == 0 || input%5 == 0){
return ("2나 5로 나눌수 있는 수 입니다.");
}
var val = 1;
while (val % input != 0 ) {
val = val * 10+1;
if(val >= 1000000000000000000 ){
return toString(val)
}
}
return "\(countElements(toString(val)))"
}
fnOnes(3);
fnOnes(7);
fnOnes(9901);
fnOnes(2);
fnOnes(9);
파이썬을 공부하면서 풀어봅니다. 다른 분들의 풀이가 깔끔하고 단순해서, 부끄럽습니다.
import unittest
def RepeatOne(x):
"""RepeatOne(1) : 1, RepeatOne(2) : 11"""
return "1" * x
def Ones(input):
x = 1
complete = False
while(not complete):
number = RepeatOne(x)
if (int(number) % input == 0):
return x
else:
x += 1
class OnesTest(unittest.TestCase):
def test_result(self):
self.assertEqual(Ones(3), 3)
self.assertEqual(Ones(7), 6)
self.assertEqual(Ones(9901), 12)
if __name__ == "__main__":
unittest.main()
public class One{
public static void main(String[] args){
int n = 3;
long max = Long.MAX_VALUE;
if(n > 0 && n < 10000) {
if(n % 2 != 0 && n % 5 != 0){
int count = countMultiple(n, max);
System.out.println(count);
}else{
System.out.println("2의 배수 혹은 5의 배수가 아닌 정수만 입력해주세요.");
}
}else{
System.out.println("0보다 크거나 10,000보다 작은 정수만 입력해주세요.");
}
}
public static int countMultiple(int n, long max) {
int count = 1;
boolean flag = true;
if(n <= 0) return count = 0;
String multipleNumber = "";
for(int i=n; i<=max && flag == true; i+=n){
count = 1;
flag = true;
int temp = i;
while(true){
if((temp - 1) % 10 == 0){
if(temp == 1){
flag = false;
break;
}else{
temp = (temp - 1) / 10;
}
count ++;
}else{
break;
}
}
if(!flag){
return count;
}
}
return 0;
}
}
def count(aaa):
i=0
while(1):
k=0
bbb=str(int(aaa)*i)
i+=1
for bb in bbb:
if bb!='1':
break
k+=1
if k==len(bbb):
return bbb
print(count(input('select')))
되게 무식하게 풀었네요;;; 9만되도 답나오는데 한참걸려요 한수배우겠습니다~~
Python 3.2.3 기준으로 작성해 보았습니다.
def one(num):
i = ret = 0
while 1:
ret += 10 ** i
if ret % num == 0:
return len(str(ret))
i += 1
print(one(3))
print(one(7))
print(one(9901))
#coding_ones.py
def check_input_number():
n=1
while 1:
try:
if n==1: num = int(raw_input('input number, not divided by 2 or 5: '))
elif n>10**8: print 'not find';return
if num%2 == 0: continue
elif num%5 == 0: continue
elif num > 10000: continue
else:
count = n*num
tmp=[]
for part in str(count):
if part != '1': tmp=[];break
tmp.append(part)
if tmp: print count;return
else: n+=1;continue
except ValueError: continue
if __name__ == '__main__':
check_input_number()
input number, not divided by 2 or 5:
3
input number, not divided by 2 or 5: 7
6
input number, not divided by 2 or 5: 9901
12
// java
public static int ones(int n) {
BigInteger allOnes = BigInteger.ONE;
BigInteger bigN = BigInteger.valueOf(n);
BigInteger ten = BigInteger.valueOf(10);
while(true) {
if(allOnes.mod(bigN).compareTo(BigInteger.ZERO) == 0)
return allOnes.toString().length();
allOnes=allOnes.multiply(ten).add(BigInteger.ONE);
}
}
파이썬으로 짜보았습니다.
def ones(n):
num = 1
count = 1
while (num % n != 0):
num = int(str(num) + '1')
count += 1
return count
while문을 이용해서 1, 11, 111, 1111, ... 이 n의 배수인지를 확인하는 방식으로 했어요~
C#으로 작성했습니다. 처음에 문제 보고 뭘 찾는 문젠가 싶을 정도로 이해하기 어려웠는데 zer6six님께서 설명을 너무 잘 해 놓으셨네요. 감사합니다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodingDojang
{
class CodingDojang
{
static void Main(string[] args)
{
Ones.Answer1(3);
Ones.Answer1(7);
Ones.Answer1(9901);
}
}
public class Ones
{
public static void Answer
(ulong n, ulong factor = 1, ulong sum = 0, int count = 1)
{
sum += factor%n;
if (sum/n > 0 && sum%n == 0) Console.WriteLine(count);
else Answer(n, factor*10, sum, ++count);
}
}
}
역으로 생각해서 11, 111, 1111을 입력된 숫자로 나눠서 찾는 방식을 취했습니다. 아마 속도면에선 이쪽이 압도적으로 빠를겁니다. BigInteger를 써서 코드가 심플해졌네요.
public class Answer
{
public static void main(String[] args)
{
try
{
DataInputStream in = new DataInputStream(System.in);
BigInteger org_num = new BigInteger(in.readLine());
for (String str = "11"; str.length() <= 100; str += "1")
{
BigInteger number = new BigInteger(str);
if (number.remainder(org_num)== BigInteger.ZERO)
{
System.out.print(number);
return;
}
}
System.out.print("cannot find");
}
catch (Exception e)
{
}
}
}
1, 11, 111...로 n값을 나눈 나머지로 계산하는 방식으로 짜봤습니다. 그런데해당 long 값 범위를 초과하는 경우가 생겨 답이 안나오는 경우가 있네요.(ex:9999) 혹 자바 코드로 다른 답변 아시는분 계시나요?? 아니면 9999 답이라두...
package my_test;
import java.util.Scanner;
public class Aa {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.print("0~10000 사이 수 입력(2의배수,5의배수x):");
int n= Integer.parseInt(scan.nextLine());
if(n%2==0||n%5==0){
System.out.println("잘못된 숫자 입력");
}else{
System.out.println("결과:"+t(n));
}
}
public static int t(int su){
int ct=1;//자리수 카운트
long temp=1;// 1,11,111,1111
while(!(temp%su==0)){
ct++;
temp=temp*10+1;
}
return ct;
}
}
파이썬 3.4 입니다.
def int_func(data):
answer = '1'
while (int(answer))%data != 0:
answer += '1'
return len(answer)
data = int(input())
print(int_func(data))
using System;
class Program
{
static int[] inputs = new int[] { 3, 7, 9901 };
static void Main()
{
Console.WriteLine("Input");
foreach (var number in inputs)
{
Console.WriteLine(number);
}
Console.WriteLine("\nOutput");
foreach (var number in inputs)
{
var target = "1";
while (true)
{
var targetNumber = Int64.Parse(target);
if (targetNumber % number == 0)
{
break;
}
target += "1";
}
Console.WriteLine(target.Length);
}
}
}
scala로 풀어보았습니다.
def one(base: Long): Int = {
def fn(number: Long): Int = {
val strNumber = number.toString
if(strNumber.forall(_ == '1'))
strNumber.size
else
fn(number + base)
}
fn(base)
}
def ones(numbers: Int*) {
numbers.foreach { n => println(one(n)) }
}
ones(3, 7, 9901)
def Ones(n):
k = n
while 1:
count = 0
lv = 0
for i in str(n):
lv += 1
if i != '1':
count = 1
n = n+k
break
if count == 0:
return lv
파이썬입니다.
def one(num):
c = 1
while True:
if int("1"*c) % num == 0:
return c
c += 1
print one(3)
print one(7)
print one(9901)
많이 느리네요. 1을 붙여가며 검사하는 좋은 방법이 있었네요...
delta = input()
n = 0
while True:
n = str(n + delta)
indi = 1
for i in range(len(n)):
if n[i] != '1':
indi = 0
break
if indi == 1:
break
n = int(n)
print len(n)
Scala
def ones(n: Int, length: Int = 1): Int = {
assert (n % 2 != 0 && n % 5 != 0)
if(BigInt("1" * length) % n == 0) length
else ones(n, length + 1)
}
ones(3) //3
ones(7) //6
ones(9901) //12
1, 11, 111, 1111... 처럼 자리수(length)를 하나씩 올리면서 해당 숫자로 나누어지는지 확인하고 나누어지면 자리수를 리턴합니다.
처음엔 아무 생각없이 순차적인 배수로 체킹을 하도록 만들다가(foo) 연산속도가 너무 느려서
1, 11, 111 ... 이런식으로 체킹을 하는방식으로(bar) 수정했더니 빠르게 잘돌아가네요 ㅎㅎ
coding by python beginner
def foo(n):
if n % 2 == 0 or n % 5 == 0 or n > 10000: return
offset = n;
s = set( list( str(n) ) )
while len(s) != 1 or int(list(s)[0]) != 1:
n += offset
s = set( list( str(n) ) )
print( len( str(n) ) )
def bar(n):
if n % 2 == 0 or n % 5 == 0 or n > 10000: return
offset = n;
while True:
t0 = ''
for i in range( len( str(n) ) + 1 ): t0 += '1'
if int(t0) % offset == 0: break
else: n += offset;
print( len( str(t0) ) )
# foo(3)
# foo(7)
# foo(9901)
bar(3)
bar(7)
bar(9901)
Using python 어이쿠 재귀에는 능력이 없어서 그냥 짜는게 편하네요..^^;
def Ones(n):
a = ""
b = 0
if n%2==0 or n%5 ==0 or 0>n or 10000<n:
print "invalid input detected!"
exit(0)
while True:
a += "1"
b = int(a)
if b%n == 0:
print len(a)
break
Ones(9901)
#데이터
n = 9901
#처리
def ones(k):
if k < 0 and 10000 < k: #0이상 10000이하의 수만가능
return "0이상 10000이하의 수만 입력해주세요"
elif k%2 == 0 or k%5 == 0: #2나 5로 나누어지는경우
return "2나 5로 나누어지지 않는 수를 입력해주세요"
else:
return one(k) #재귀함수 시작합세
def one(k, m=1, a=0, length=0): #단지 수학적인 내용임
a = a + m%k
length = length + 1
if a%k==0:
return length
else:
return one(k,m*10,a,length) #재귀함수만 좀 사용했을뿐
#입출력
print(ones(n))
def one(l,count=0,val=0):
count+=1
val=val*10+1
if val%l==0:
return count
else:
return one(l,count,val)
print one(9901)
파이선 2.7입니다 ㅎㅎ
#include <stdio.h>
int remaind(int b);
int main(void)
{
int n;
printf("Please insert a number between 1 and 10000.\n: ");
scanf("%d", &n);
if((n % 2) == 0 || (n % 5) == 0)
{
printf("\n\nInvalid.");
exit(1);
}
int ansbase = remaind(n);
printf("\n");
int ii;
for(ii = 0; ii < ansbase ; ii++)
{
printf("1");
}
return 0;
}
int remaind(int b)
{
int i=1;
int summ = 0;
int multip = 0;
for(;;)
{
multip++;
summ = summ + (i % b);
if((summ % b) == 0)
{
break;
}
i = i * 10;
}
return multip;
}
C로 작성했습니다. 어떤 수 'n'을 입력받았을 때, 그 수 n으로 각 자릿수를 나눈 나머지가 모두 1이 되도록 하는 것이 관건이므로, 우선 모든 자릿수의 값(=n%10, n%100, n%1000, ...)이 1이 될 때 그 자릿수가 총 얼마인지를 알고자 했습니다. 일단 그 자릿수를 구하고 나면, 그 자릿수의 "111...111" 값이 최소의 배수가 될 것입니다. 그래서 reamaind라는 함수를 짜고, 그 값을 계산한 다음 그 자릿수만큼 '1'을 출력했습니다.
raw = input() #1~10000까지의 숫자를 입력 받음
num = 1
digit = 1
while True:
if num%raw == 0:
break
else:
num = num*10 + 1 #num의 자리수를 계속해서 증가시킴
digit += 1
print digit #자리수를 출력
n = int(input('Enter n: '))
if n%2 == 0 or n%5 == 0:
print('wrong number')
else:
i = 2
while True:
M = int('1'*i)
if M%n == 0:
print(i)
break
else:
i += 1
def check(n):
for i in str(n):
if i != '1':
return False
break
else:
return True
n = input("input a number, not divisible by 2 or 5, between 0 and 100,000:")
result = n
while check(result) == False:
result = result + n
print list(str(result)).count("1")
많이 배워야겠습니다.
Ruby
ones= ->f,num='1' { num.to_i%f==0 ? num.size : ones[f,num+'1'] }
Test
expect([3,7,9901].map(&ones)).to eq [3,6,12]
파이썬3.4입니다. 어떻게 하면 range(1, 100000000000..)처럼 지저분하게 하지않고, 무한대로 늘릴수있을까 고민했는데, while에 조건문을 써서 하는 방법이 있었네요. 많이 배웠습니다.
while True:
n = int(input('? '))
if n % 2 != 0 and n % 5 != 0 and n <= 10000:
for i in range(1, 1000000000000000000000):
if int('1' * i) % n == 0:
print(i)
break
else:
continue
다시 짜보았습니다.
from itertools import count
def gen_str_1():
for n in count(1):
yield int('1' * n) #1, 11, 111, 1111, ...
def chk(n):
if n % 2 == 0 or n % 5 == 0 or n < 0 or n > 10000:
return False
for ones in gen_str_1():
if ones % n == 0:
return len(str(ones))
chk(3)
2016-10-20
def f(n):
assert 0 <= n <= 10**4
assert n%2 and n%5
ones = '1'
while 1:
if int(ones)%n == 0:
return len(ones)
ones += '1'
print(f(3), f(7), f(9901), sep='\n')
int solution(int n) {
int result = n;
int digit;
while(!isAll1(result)) {
result += n;
System.out.println(result);
}
digit = countDigit(result);
return digit;
}
private boolean isAll1(int n) {
while(n >= 1) {
if(n % 10 == 1) {
n = n / 10;
}
else {
return false;
}
}
return true;
}
private int countDigit(int n) {
int count = 0;
while(n > 0) {
n = n / 10;
count++;
}
return count;
}
너무 막 짜서 부끄럽지만, 다른 분들 코드 보면서 공부 해야겠네요!
public class Ones {
public long getOnes(long num){
if(num % 2 == 0 || num % 5 ==0 || num > 10000 )
return 0;
int i = 2;
long result = 0 ;
while(true){
result = num * i;
i++;
if(checkOnes(result))
{
System.out.println(result);
break;
}
}
return (result+"").length();
}
public boolean checkOnes(long num){
String result = num +"";
char check[] = result.toCharArray();
for(int i = 0 ; i< check.length ;i++){
if(check[i] !='1')
return false;
}
return true;
}
}
def gen_1(x = 1):
while 1:
yield int('1'*x)
x += 1
while __name__ == '__main__':
num = int(input('>>>'))
for x in gen_1():
if x%num == 0:
print(len(str(x)))
break
제네레이터 이용. 파이썬 3.5.1
# 파이썬 3.5.1
def do(a):
x = '1'
while int(x) % a != 0: x += '1'
return len(x)
for i in [3,7,9901]:
print(do(i))
Python 3.4
def Ones(num, ones = 0):
ones = (ones * 10) + 1
if ones % num == 0:
print(len(str(ones)))
else:
Ones(num, ones)
Ones(int(input()))
import time
import re
t1=time.time()
n=int(input())
if n%2 and n%5:
p=re.compile(r"^1(?=1)*[1]*$")
k=n
while True:
test=p.match(str(n))
if test:
print("Number=",n)
break
n=n+k
print("Length=",len(str(n)))
t2=time.time()
print("Calculation time=",t2-t1)
else:
print("2 or 5")
t1=time.time()
b="1"
while int(b)%n != 0:
b=b+"1"
t2=time.time()
print("number=",b)
print("length=",len(b))
print("Calculation time=",t2-t1)
def ones(x, allones=""):
if x%2 ==0 or x%5 ==0 : return ValueError
allones = allones + '1'
if eval(allones) % x == 0 : return len(allones)
else : return ones(x, allones)
재민스님의 아이디어를 활용해보았습니다. 굳이 숫자를 계속 끌고오면서 필요할때마다 문자로 변환하는것보다, 문자로 활용하다가 필요할 때에 숫자로 변환하는게 간단할것 같아서 그 부분만 뒤집어 보았습니다.
그리고 2,5의 배수를 입력하면 valueerror를 반환하도록 해 보았습니다.
def 배수(input_a):
a,b=1,1
while 1:
if a%input_a == 0:
return print(str(a).count("1"))
a=a+10**b
b+=1
배수(3)
배수(7)
배수(9901)
Python 3.5.2
파이썬 코드입니다. 처음엔 1로 이루어진 수들의 리스트로 후보들을 만들고, 그안에서 찾아내는 방식으로 코딩을 했습니다.
n = int(input())
candi = [int((10**x-1)/9) for x in range(1,21)]
for i in range(len(candi)):
if candi[i]%n == 0:
print(i+1)
break
그다음에는 따로 후보를 만들 것 없이 한줄로 처리해봤습니다.
n = int(input())
i = 1
while True:
if int((10**i-1)/9)%n == 0:
print(i)
break
i += 1
파이썬 초보입니다. 많은 피드백 부탁드립니다.
public class Ones {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int max = 10000;
int ans;
for (int i = 0; i <= max; i++) {
if (i%2 != 0 && i%5 != 0) {
for (int j = 1; ; j++) {
ans = countAllOnes(i*j);
if(ans != 0){
System.out.println("ans : " + i + ", "+ ans);
break;
}
}
}
}
}
private static int countAllOnes(int val){
int count = 0;
do {
if (val % 10 == 1) {
val /= 10;
count++;
}else {
return 0;
}
} while (val > 0);
return count;
}
}
Func<ulong, ulong> getOnesSize = (mod) => Enumerable.Range(1, 19).Select(k => Convert.ToUInt64(new string('1', k))).Where(k => k % mod == 0).FirstOrDefault();
ulong value = getOnesSize(9901);
Console.WriteLine(value > 0 ? value.ToString().Length : -1);
in_ = [3,7,9901]
for i in in_:
v = i
while len(str(v)) != str(v).count('1'):
v+=i
print(len(str(v)))
무식하게 풀었는데 다른분의 풀이를 보고 역으로 생각하니 빠르고 좋네요 다시 작성했습니다.
in_ = [3,7,9901]
for i in in_:
b = '1'
while int(b) % i != 0:
b+='1'
print (len(b))
Python 3.5.2에서 작성하였습니다.
def num(n):
a = 1
while True:
if str(n*a) == "1" * len(list(str(n*a))) :
return len(list(str(n*a)))
break
else : a+=1
nums,result = [3,7,9901],0
for x in nums:
while str(result).count('1') != len(str(result)):
result += x
print(len(str(result)))
result = 0
#### 2016.12.16 D-433 ####
좀더 간략화하는 방법없을까 했는데... 이런 아예 생각을 바꾸면됫었군요! (모든자리수가 1로채워진 수) % n == 0 흠.. 역시 문제하나하나 깊게 생각하는 시간은 필수인것같습니다!ㅎ
매트랩으로 도전하였습니다. 111은 3의 배수, 111111은 7의 배수이므로 자연수 n을 입력 받았을때 1부터 11, 111, 1111 계속 계산하여 찾는 방식으로 구하였습니다.
n = input('# 3) Input number :');
[exp x] = deal(1);
for i = 1 : 10^5
if (mod(n, 2)==0) || (mod(n, 5)==0) % 2 or 5의 배수를 입력받으면 다시 입력
n = input('Input number :');
continue
elseif mod(x, n) == 0
break
end
x = x + 10^exp; % ex) 111 = 11 + 100
exp = exp + 1;
end
disp(i)
public class Ones {
public static void main(String[] args){
int n=9901;
int res=1;
String ones=new String("1");
while(Long.parseLong(ones) % n != 0){
ones=ones.concat("1");
res+=1;
}
System.out.println(res);
}
}
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void main() {
double n = 9901;
double temp = 1;
int i = 0;
while(i<13) {
i++;
if(0==fmod(temp,n))
break;
temp = temp * 10 +1;
}
printf("%d", i+1);
}
import java.util.Arrays;
import java.util.Scanner;
public class Ones {
public static void main(String[] args) {
long n = new Scanner(System.in).nextLong();
long c = 0;
while (true) {
long nc = n * c;
String[] snc = String.valueOf(nc).split("");
if (Arrays.asList(snc).stream().allMatch(i -> i.equals("1"))) {
System.out.println(snc.length);
break;
}
c++;
}
}
}
파이썬 3.5.3 연습용 코드입니다.
n = 0
a = ''
arg='1'*10000
def getstr():
global n
global a
if n == 0:
a = input("2나 5로 나눌 수 없는 0이상 10,000 이하의 정수를 입력하세요 : ")
if int(a) % 2 == 0 or int(a) % 5 == 0:
n += 1
getstr()
elif n > 0:
a = input("다시 입력하세요 : ")
if int(a) % 2 == 0 or int(a) % 5 == 0:
getstr()
else:
n = 0
getstr()
while 1>0:
for x in range(1,10000):
if int(arg[0:x+1]) % int(a) == 0:
print(len(arg[0:x+1]))
break
break
정계산으로 하면 너무 많은 메모리가 소모되므로 역으로 계산. 2와 5의 배수가 아닌 10000 이하의 정수를 n으로 받고, 이 n으로 11, 111,1111, .... 111111~ 을 나누었을때 나머지가 0이 되는 값을 찾음.
import java.util.*;
public class onecounter {
public static void variable(){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String one_num = "";
while (true){
one_num += "1";
if (Long.parseLong(one_num)%n == 0){System.out.println(one_num.length());break;}
else {continue;}
}
}
public static void main(String[] args){
onecounter.variable();
}
}
public class Ones {
private static boolean divide_two_five(int n) {
if (n%2==0||n%5==0){
return false;
}
return true;
}
private static int f_one(int n) {
if (n<0||n>10000){return -2;}
if (!(divide_two_five(n))){return -1;}
int count_ten = 1;
long number = 1;
while (!(number%n==0)){
number = (long) (number + Math.pow(10, count_ten));
count_ten++;
}
return count_ten;
}
public static void main(String[] args) {
System.out.println(f_one(3));
System.out.println(f_one(7));
System.out.println(f_one(9901));
//0보다 작거나 10000보다 크면 -2
//2나 5로 나눠지면 -1
System.out.println(f_one(9900));
}
}
private static void getMinAllOne(int input){
if(input < 0 || input > 10000){
System.out.println("0 이상 10000 이하의 수를 입력하세요.");
}else{
if(input%2==0 || input%5==0){
System.out.println("2 또는 5로 나눌수 있는 수 입니다.");
}else{
String allOne = "";
while(true){
allOne += "1";
if(allOne.length() < 21){
if(Long.parseUnsignedLong(allOne) % input == 0){
break;
}
}else{ //UnsignedLong 범위를 벗어나는 경우
BigInteger parseAllOne = new BigInteger(allOne);
if(parseAllOne.mod(BigInteger.valueOf(input)) == BigInteger.ZERO){
break;
}
}
}
System.out.println(allOne.length());
}
}
}
n = input("Input is:")
def distinguish(n):
if n == 2 or n == 5:
return False
else:
target = '1'
index = 1
while int(target) % int(n) != 0:
target += '1'
index += 1
return index
print(distinguish(n))
Python 3.6 최소는 1, 11, 111,... 이므로 입력수의 자릿수만큼 시작합니다.
def Ones(n):
ones = '1'*len(str(n))
while int(ones) % n != 0:
ones += '1'
return ones.count('1')
>>> Ones(3)
3
>>> Ones(7)
6
>>> Ones(9901)
12
>>> Ones(11)
2
>>> Ones(1111)
4
>>> Ones(1)
1
javascript
var ones = function(n) {
for (var i = 1; i % n > 0; i += "1") /* do nothing */ ;
return i.length;
};
console.log(ones(3));
console.log(ones(7));
console.log(ones(9901));
// 111111 - C#
using System;
namespace OneoNeonE
{
class Program
{
static long inputter(long n)
{
long i;
for (i = 1; true; i++)
{
if (checker(n * i))
break;
}
return (long)Math.Log10(n * i) + 1;
}
static bool checker(long n)
{
for (int i = 0; i < (long)Math.Log10(n) + 1; i++)
{
if (n / (long)Math.Pow(10, i) % 10 != 1)
return false;
}
return true;
}
static void Main(string[] args)
{
Console.WriteLine("ready>>"); long n;
do
{
n = long.Parse(Console.ReadLine());
} while (n % 2 == 0 || n % 5 == 0 || n < 0 || n > 10000);
Console.WriteLine(inputter(n));
}
}
}
num = int(input('Enter number: ')) #Python
originalNum = num
result = True
while result == True:
for i in str(num):
if i == '1':
result = False
continue
else:
result = True
num += originalNum
break
print(len(str(num)))
def ones(n):
m = n
while set(str(m)) != {'1'}:
m += n
return len(str(m))
print(ones(9901))
# 컨닝
def ones2(s, n):
return len(s) if int(s) % n == 0 else ones2(s + '1', n)
print(ones2('1', 9901))
n = int(input("any number : "))
if n % 2 == 0 or n % 5 == 0 or 10000 < n :
print("invalid number")
else :
m = 1
while True :
i = n * m
a = str(i)
if a.count('1') == len(a) :
break
else :
m += 1
continue
print(len(a))
결과는 제대로 나오는데 루프 빠져나오는 데까지 상당한 시간이 걸리는 경우도 있네요. 혹시 문제가 있는 부분이 있다면 지적해주시면 감사하겠습니다.
좋은 알고리즘 이였습니다
#include <iostream>
#include <string>
using namespace std;
int find(int &num) {
int ans=1;
string cnt = "";
while (stoull(cnt.append("1")) % num!=0) {
//cout << cnt << endl;
ans++;
}
return ans;
}
int main() {
int num;
cin >> num;
if(num>=0 && num<=10000 && num%2 !=0 && num%5 !=0) cout << "input : " << num << " find : " << find(num) << endl;
else cout << "wrong" << endl;
return 0;
}
package codingdojang;
import java.util.Scanner;
public class ex44 {
public static boolean check(long num) {
String temp = Long.toString(num);
for(int i=0; i<temp.length(); i++) {
if(temp.charAt(i) != '1') return false;
}
return true;
}
public static int count(long num) {
int count = 0;
while(num != 0) {
num = num/10;
count++;
}
return count;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long n = sc.nextLong(); sc.nextLine();
long bae = n;
while(true) {
if(check(n+bae)) {
System.out.println(count(n+bae));
return;
}
n = n + bae;
}
}
}
public class Program {
public static long ones( int number ) {
int value = 1;
int n = 1;
int numberOfOne = 1;
while( n % number != 0) {
value *= 10;
n += value % number;
++numberOfOne;
}
return numberOfOne;
}
public static void main(String[] args) {
System.out.println(ones(7));
}
}
- 단순무식-
a=input()
f=0
while True:
f=f+int(a)
s=[]
for i in str(f):
s.append(i)
k=set(s)
if k=={'1'}:break
print(len(s))
-발상의 전환-
a=input()
h=1
while h%int(a)!=0:
h=(h*10)+1
print(len(str(h)))
while True:
num=int(input())
if num%10 and 0<=num<=1e4:
break
tmp=int(num)
while True:
if set(list(str(tmp)))=={'1'}:
print(len(str(tmp)))
break
tmp+=num
#최적화
#tmp=1
#while True:
# if not tmp%num:
# print(len(str(tmp)))
# break
# else: tmp=tmp*10+1
무식하게 했다가 다른분들 한걸보고 난 왜 이런건가...
파이썬 3.6
def inputdata(datalist):
data = int(input(''))
if data < 0 or data > 10000: return
datalist.append(data)
inputdata(datalist)
def main(datalist):
for n in datalist:
multiple = 0
m = 1
if n%2 != 0 or n%5 != 0:
while set(list(str(multiple))) - {'1'}:
multiple = n * m
m += 1
print(len(list(str(multiple))))
if __name__ == "__main__":
datalist =[]
try:
inputdata(datalist)
except ValueError:
print("")
main(datalist)
3
7
9901
3
6
12
r로 풀었습니다.
```{r}
f1<-function(n){
if(n%%2!=0&n%%5!=0){
t<-trunc(log10(n))
repeat{
s<-0
for(l in 0:t){
s<-s+10**l }
if(s%%n==0){
print(t+1)
break }
t<-t+1
} }else{
print("입력값이 2 또는 5의 배수입니다") } }
f1(9901)
```
# 파이썬
def ones(n, m="1"):
if int(m) % n == 0: return len(m)
return ones(n, m+"1")
print(ones(3))
print(ones(7))
print(ones(9901))
def one(n):
a = 1
result = 1
while 1:
result = ((10**a-1)/9)%n
if result == 0:
break
a += 1
return a
m = int(input())
print(one(m))
N_list=[]
line_num=int(input("입력하려는 숫자의 개수를 입력하세요\n"))
for line in range(line_num):
N=int(input())
if N%2==0 or N%5==0:
N=int(input("다시 입력하세요"))
N_list.append(N)
def solve(n):
counter=2
check_str='11'
flag=1
while flag:
if int(check_str)%n==0:
return counter
flag=0
else:
check_str+="1"
counter+=1
for num in N_list:
print(solve(num))
import java.util.Scanner;
public class Ones {
public static boolean checker(long num){
int forCount = (int) Math.log10(num);
boolean flag = true;
if(forCount < 1){
if(num != 1){
flag = false;
return flag;
}else{
flag = true;
return flag;
}
}else{
for(int i = 0; i< forCount+1; i++ ){
if(num % 10 != 1){
flag = false;
break;
}else{
num /= 10;
continue;
}
}
}
return flag;
}
public static void execute(long num){
int count = 1;
boolean result = checker(num);
while(!result){
result = checker(num * count++);
}
System.out.println((int) Math.log10(num* count-1) +1);
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
for(int i=0; i<3; i++){
long num = sc.nextInt();
execute(num);
}
sc.close();
}
}
// Ones
package main
import (
"fmt"
"strconv"
)
func getMinOnes(num int) int {
numStr := "1"
for {
if val, _ := strconv.Atoi(numStr); val%num == 0 {
return len(numStr)
} else {
numStr += "1"
}
}
}
func main() {
fmt.Println(getMinOnes(3))
fmt.Println(getMinOnes(7))
fmt.Println(getMinOnes(9901))
}
while True:
n = int(input('일의자리가 1, 3, 7, 9 인 자연수를 입력하세요.(끝내려면 0을 입력하세요.) : '))
if not n:
print('End')
break
i = 1
while True:
if i > 1000000:
break
if not set(str(n * i)) - {'1'}:
print(len(str(n * i)), '자리')
break
i += 1
def ones(n):
add = n
while int('2'*len(str(add))) % add != 0:
add += n
return len(str(add))
Python 3
import java.util.Scanner;
import java.math.BigInteger;
public class Ones{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
String a = "";
int i = 1;
while(true){
int count = 0;
BigInteger b = new BigInteger(input *i + "");
a = b.toString();
for(int j=0;j<a.length();j++){
if(a.charAt(j) == '1')
count++;
}
if(count == a.length())
break;
i++;
}
System.out.println(a);
System.out.println(a.length());
}
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true) {
long n = Long.parseLong(br.readLine());
if (n == 0) break;
if (n % 2 == 0 || n % 5 == 0) continue;
long allOne = 1;
while(allOne % n != 0) {
allOne = Long.parseLong(allOne+"1");
}
System.out.println((allOne+"").length());
}
} // 자바입니다. 바로바로 나오네요. 1 > 11 > 111 식으로 증가시킨다음 그 값이 입력값으로 나눠지면 출력하게 했습니다
public class Ones {
public static long ones( int number ) {
int value = 1;
int n = 1;
int numberOfOne = 1;
while( n % number != 0) {
value *= 10;
n += value % number;
++numberOfOne;
}
return numberOfOne;
}
public static void main(String[] args) {
System.out.println(ones(7));
}
}
package h_Ones;
import java.util.Scanner;
public class Ones {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int L=30;//입력값 수 제한
int l,i,j,N; long n;
long input[]=new long[L];
System.out.println("To stop inputting, input 0.");
for(l=0;l<L;l++){ input[l]=in.nextLong(); if(input[l]==0) break;} //입력
for(i=0;i<l;i++){
/*Algorithm*/
N=-1;
do{
N++;
n=1; for(j=1;j<N;j++) n=n*10+1; //n= 1로만 이루어진 N자리의 수
}while(n%input[i]!=0);
System.out.print(N+" ");
/*Algorithm ends*/
} System.out.println(" end. l:"+l);
}}
Swift입니다.
만 이하의 숫자가 주어진 경우 언제나 조건을 만족하는 1로만 구성된 숫자가 있다고 가정했습니다. 1, 11, 111, 1111로 증가하면서 주어진 숫자로 나눌 수 있는지를 봤습니다.
func findNumber(_ number:Int) {
var s = 1
while s % number != 0{
s = s * 10 + 1
}
print("\(number) ==> \(s) ==> length \(String(s).count)")
}
findNumber(3)
findNumber(7)
findNumber(9901)
결과는...
3 ==> 111 ==> length 3
7 ==> 111111 ==> length 6
9901 ==> 111111111111 ==> length 12
Python
test = [3, 7, 9901]
for t in test:
a = "1"
while True:
if int(a)%t == 0:
break
else:
a += "1"
print(len(a))
// Ones
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Ones(3);
Ones(7);
//Ones(9901);
}
public static void Ones(long n)
{
long count = 1;
while(true)
{
long num = n * count++;
long len = (long)(Math.log10((num)) + 1);
String st = "";
for(long i = 0; i < len; i++)
{
st += "1";
}
System.out.println(num+" : "+ count +" : "+st);
if(st.equals(String.valueOf(num)))
{
System.out.println(len);
break;
}
}
}
}
숫자가 커질수록 오래걸리네요ㅜ
떠오르는대로 만들었는데 너무 오래걸리네요 다른분들 코드를 보고 공부해봐야 겠습니다.
n=int(input("input:")) #입력
s1=set('1')
s2=set()
i=0
while s1!=s2:
s=str(n*(i+1))
len_s=len(s)
s2=set()
for j in range(len_s):
s2.add(s[j])
if s2==s1:
print("length:",len_s)
break
i=i+1
풀이를 보고 입력 개념을 반대로 했더니 연산 속도가 이렇게 주네요... 부끄럽습니다.ㅋ 13.887s → 0.222s
def a(n):
m = 0
while True :
m += 1
if str(n * m).count('1') == len(str(n * m)):
return len(str(n * m))
package test;
public class test {
public static void main(String[] args) {
System.out.println(Check(9139, 1L));
}
private static int Check(int num, Long i) {
return i % num == 0 ? (i + "").length() : (i + "").length() > 18 ? 0 : Check(num, i * 10 + 1);
}
}
Long abc = 8547L;
for (Long i = abc;; i++) {
if (i % abc == 0) {
Long num = i;
boolean ha = true;
int temp = (num + "").length();
for (int j = 0; j < temp; j++) {
if (num % 10 == 1) {
num /= 10;
} else {
ha = false;
break;
}
}
if (ha) {
System.out.println(i);
break;
}
}
}
C#
using System;
namespace CD044
{
class Program
{
static void Main()
{
Console.WriteLine(GetMinOnesLength(3));
Console.WriteLine(GetMinOnesLength(7));
Console.WriteLine(GetMinOnesLength(9901));
}
static int GetMinOnesLength(int aNumber)
{
string ones = "1";
while (long.Parse(ones) % aNumber != 0) { ones += "1"; }
return ones.Length;
}
}
}
def Ones(n) :
# n 전제 조건
if (n % 2 ==0 or n%5 ==0 ) :
return "2 또는 5로 나누어 지면 안됩니다."
elif (n<0 or n>10000) :
return "숫자 범위를 벗어났습니다."
# 나누어 지는 수가 모두 1로 이루어 진 경우
else :
# n의 길이 만큼 1로 이루어진 문자 생성
str_one = "1"*len(str(n))
while 1:
if int(str_one) % n == 0 :
return len(str_one)
str_one +="1"
def ones(n):
r='11'
f=1
while f:
if int(r) % n == 0:
print(len(r))
f=0
else:
r+='1'
ones(3)
ones(7)
ones(9901)
public class KimSanghyeop
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("숫자 입력");
int num;
do
{
num= sc.nextInt();
}while (num %2 ==0 || num%5 ==0);
long res = 1 ;
int cnt =1;
Math.pow(10,2);
while (res % num !=0)
{
res +=Math.pow(10, cnt);
cnt+=1;
}
System.out.println("횟수 : "+cnt);
}
}
def least_one(n):
i = 0
solution = []
while True:
i += 1
if n > 10000:
break
if i % 2 == 0 | i % 5 == 0:
continue
if n % 2 == 0 | i % 5 == 0:
raise Exception('2 또는 5의 배수는 입력하시면 안 됩니다.')
num_list = []
for j in list(str(n * i)):
int_j = int(j)
if int_j == 1:
num_list.append(int_j)
if len(num_list) == len(str(n * i)):
solution.append(str(n * i))
break
return len(solution[0])
def Cal_ones(num):
ndigit = 1
while True:
Ones = int('1' * ndigit)
if Ones % num == 0:
break
ndigit += 1
print(len(str(Ones)), Ones)
Cal_ones(7)
답 : 6
def function(n):
x = '1'
while True:
if int(x) % n == 0:
return len(x)
else:
x += '1'
n = int(input())
if n % 2 == 0 or n % 5 == 0:
raise Exception('2 or 5 multiple')
elif n < 0 or n > 10000:
raise Exception('not in range')
print(function(n))
while True:
n=int(input("Input a positive integer: "))
i=1
ones=1
while True:
if ones%n==0: break
ones+=10**i
i+=1
print(i)
namespace codingdojang__
{
class Program
{
static void Main(string[] args)
{
Ones(3);
Ones(7);
Ones(9901);
}
static void Ones(int input)
{
string temp = "1";
long count = 1;
bool found = false;
while (found == false)
{
if (long.Parse(temp) % input == 0)
{
found = true;
}
else
{
temp += "1";
count++;
}
}
Console.WriteLine(count);
}
}
}
1로만 이루어진 수들을 1부터 차례대로 n으로 나누어본다. 나누어떨어질 때까지 반복한다.
def Ones(n):
p = 0
k = 0
while True:
p += pow(10, k)
if p%n == 0:
return k+1
else:
k += 1
print(Ones(9901))
def ones(n):
data='1'
while(True):
data=int(data)
if data%n==0:
data=str(data)
print(len(data))
break
else:
data=str(data)
data=data+'1'
ones(3)
ones(7)
ones(9901)
import java.util.Scanner;
public class Ones {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n;
while(true) {
System.out.println("2와 5의 배수가 아닌 10000보다 작은 정수 입력 : ");
n = scanner.nextInt();
if(n % 2 != 0 && n % 5 != 0) break;
}
long x = 1, y = 10;
int count = 1;
while(true) {
if(x % n == 0) break;
else {
x += y;
y *= 10;
count++;
}
}
System.out.println(count);
}
}
def ones(n):
num_with_ones = 1
power = 1
while 1:
if num_with_ones%n!=0 :
num_with_ones+=10**power
power+=1
continue
else:
return(len(str(num_with_ones)))
def order(n):
order = 1
while True:
if not int('1'*order) % n == 0:
order += 1
else:
return order
break
print(order(9901))
inp, n= int(input("input : ")), '1'
while True :
if int(n)%inp == 0 :
print(len(n))
break
else :
n += '1'
결과
input : 9901 12
하고나서 다른분들 답 보니까 똑같은게 있네요 ㅠㅠㅠ
n = int(input("1~10000 사이 숫자 입력 : "))
result = 0
Run = True
if n % 2 != 0 or n%5 != 0 :
while Run :
result = result + n
if str(result) == "1" * len(str(result)):
print(len(str(result)))
break
import java.util.*;
public class Ones {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
StringBuffer str = new StringBuffer();
str.append("1");
Double n = 0.0;
if(num%2!=0&&num%5!=0) {
for(int i=1;;i++) {
str.append("1");
n = Double.valueOf(str.toString());//스트링버퍼를 스트링으로 만들고 정수로
if(n%num==0) {
System.out.println(str.length());
break;
}
}
}
}
}
파이썬 3입니다.
일단 input으로 원하는 숫자를 받습니다. (n으로 저장)
n = int(input())
저는 이 문제를 푸는 두 가지 방법을 생각했습니다.
--- 첫번째 풀이 ---
첫 번째 풀이는 n의 배수를 모두 체크하는 방법입니다. str(n의 배수)을 집합으로 만들어서 1만 존재하는지 체크했습니다.
if n == 1:
print(1)
elif n % 2 == 0 or n % 5 == 0:
print('잘못된 입력')
else: # 모든 n의 배수를 체크한다
m = n
while set(str(m)) != {'1'}:
m += n
print(len(str(m)))
--- 두번째 풀이 ---
이 풀이는 n에 어떤 수를 곱해야 되는지를 직접 구하는 방법입니다.
설명하자면 n에 어떤 수를 곱해서 일의 자리를 1로 맞춘 다음, N = (그 곱수) * n에 저장하고,
N의 십의 자리를 마찬가지로 1로 맞추기 위해 (십의 자리 곱수)를 구하고, N += (10^1) * (십의 자리 곱수) * n 을 하고, ...
이런 과정을 거쳐서 최종적으로 N이 11111..이 된다면 자리수를 리턴하는 방법입니다.
if n == 1:
print(1)
elif n % 2 == 0 or n % 5 == 0:
print('잘못된 입력')
else: # 일의 자리수를 1로 맞추고 그 이후에 10의 자리수를 1로 맞추고... 반복해서 전체가 1이 되도록 한다
s_n = str(n)
N = n * ((s_n[-1] == '1') + (s_n[-1] == '3') * 7 + (s_n[-1] == '7') * 3 + (s_n[-1] == '9') * 9) # n의 일의자리 수를 1로 만들기 위해 숫자를 곱한 결과
print('처음 N = {}'.format(N))
i = 1 # 판별할 자리수: N의 일의자리 판별이 끝났으니 십의 자리부터 판별한다.
while set(str(N)) != {'1'}: # N이 1로만 이루어질 때까지 반복
mul = 0 # N의 10^i의 자리수에 곱해야 하는 수
while (int(str(N)[-i-1]) + mul * int(s_n[-1])) % 10 != 1: # 적절한 mul 찾기
mul += 1
N += mul * (10**i) * n
print('N = {}'.format(N))
i += 1
print(len(str(N)))
n=int(input("2나 5의 배수가 아닌 n(0<n<10000)을 입력하십시오: ")) #9901
ones="1"
while True: #모든 자리의 숫자가 1인 숫자들을 n으로 나눠서 떨어지는 지 확인
if n%2==0 or n%5==0 or n<=0 or n>=10000:
print("잘못된 n을 입력하셨습니다.")
break
if int(ones)%n==0:
print(len(ones)) #12
break
ones+="1"
n = 9901
multiple = []
while 1:
multiple.append('1')
mul = int(''.join(multiple))
if mul % n == 0:
print(len(multiple))
break
while True:
number = int(input('Enter number: '))
if number % 2 == 0 or number % 5 == 0 or number >10000:
print('please enter the number again!')
continue
else:
j = 0
digit = 0
while True:
j += 10 ** digit
if j % number == 0:
print('number:{}, digit:{}'.format(number, digit+1))
break
digit += 1
파이썬으로 작성하였습니다 1~10000사이에서 입력받은 숫자가 2와 5의 배수가 아닌 경우 1로만 이뤄진 수의 자리수를 늘려가면서 나누어 나머지가 0이 되면 그 수의 자리수를 출력하는 형태로 작성하였습니다
def two(num):
count=0
for i in range(len(num)):
if num[i]!="1":
count=0
break
else:
count+=1
return count
n=int(input())
i=0
while True:
if i%2!=0 and i%5!=0 and i%n==0:
count=two(str(i))
if count!=0:
print(count)
break
i+=1
def find_ones_num(n):
ones_num_list = ["1"]
while int(ones_num_list[-1]) % n != 0:
ones_num_list.append(ones_num_list[-1] + "1")
return len(ones_num_list[-1])
파이썬3입니다.
import random as r
n = r.sample([x for x in range(1, 10000) if x % 2 != 0 and x % 5 != 0], 1)[0]
m = 1
x = 0
while m:
if m % n == 0:
break
x += 1
m += 10**x
print(
f'n is {n}.\nLeast common multiple having only \'1\'.\nThe digit is {str(m).count("1")}'
)
package Test;
import java.math.BigInteger;
public class Test3 {
public static void main(String[] args) {
BigInteger n = new BigInteger("3");
BigInteger m = new BigInteger("7");
BigInteger x = new BigInteger("9901");
BigInteger temp_n = n;
BigInteger temp_m = m;
BigInteger temp_x = x;
while(!digit(n)) n = n.add(temp_n);
while(!digit(m)) m = m.add(temp_m);
while(!digit(x)) x = x.add(temp_x);
System.out.println(get_digit(n));
System.out.println(get_digit(m));
System.out.println(get_digit(x));
}
public static int get_digit(BigInteger input) {
int result = 1;
while(input.compareTo(BigInteger.TEN) == 1) {
input = input.divide(BigInteger.TEN);
result++;
}
return result;
}
public static boolean digit(BigInteger input) {
boolean result = true;
while(true) {
if(input.compareTo(BigInteger.TEN) == -1) {
if(!input.equals(BigInteger.ONE)) result = false; break;
} else {
if(!input.remainder(BigInteger.TEN).equals(BigInteger.ONE)) {
result = false;
break;
}
else input = input.divide(BigInteger.TEN);
}
}
return result;
}
}
Input = int(input())
k = 1
a = set(sorted(str(Input)))
while len(a) != 1 or '1' not in a :
key = Input*k
a = set(sorted(str(key)))
k = k+1
print(str(key).count('1'))
def ones(n):
k = 2
if n % 2 != 0 or n % 5 != 0:
while 1:
if str(n*k) == "1"*len(str(n*k)):
print(len(str(n*k)))
break
k += 1
ones(3)
ones(77)
ones(9901)
def function(number):
num = int(number)
if num % 2 == 0 or num % 5 == 0:
print('WRONG INPUT')
else:
while True:
num += int(number)
# print(num)
# print(list(str(num)),set(list(str(num))))
if set(list(str(num))) == {'1'}:
print('FOUND for {} : {}, {}자리'.format(number, num, len(list(str(num)))))
break
function(3)
def Ones(number):
b="1"
while int(b)%number != 0:
b+="1"
return len(b)
print(Ones(3))
print(Ones(7))
print(Ones(9901))
import numpy as np
flag = True
n = 3
end = np.array([x for x in range(1,10) if str(n*x)[-1]=='1'])
end
while flag:
for i in end:
temp = str(i*n)
if temp=='1'*len(temp):
print(len(temp))
flag = False
break
end+=10
def ones(n):
i = 0
while True:
num = n * i # 111
if set(str(num)) == {'1'}:
break
i += 1
return len(str(num))
if __name__ == '__main__':
print(ones(3))
print(ones(7))
print(ones(9901))
a = range(10001) # 참조할 b 리스트
b=[]
for i in a:
if i%2 !=0 and i%5 !=0:
b.append(i)
q = int(input("b 리스트를 참조해 2와 5로 나누어 지지않는 숫자를 입력하세요 : "))
j=0
d="1"
while True:
w=d+"1"
d=w
a = int(d)//q
if int(d) ==a*q :
print("숫자는 %d 함수를 이용한 수는 %s , 숫자의 길이는 %d 입니다" %(q,d,len(d)))
break
else:
continue
def count_ones(n):
a = 1
while True:
if a%n !=0 :
a = int(str(a)+"1")
else:
break
return len(str(a))
#codingdojing_ones
#1. 계속 숫자를 더해서 각 자리가 1인지 확인하기
#2. 1, 11 ,111, ...을 n으로 나눠서 나머지가 0인거 구하기
n = int(input('n?: '))
ones = '1'
while True:
if int(ones) % n == 0:
print(len(ones), ones)
break
else:
ones += '1'
num = int(input('수 입력: '))
one_num = 1
while int('1'*one_num) % num: one_num += 1
print(one_num)
실행 결과입니다.
수 입력: 3
3
수 입력: 7
6
수 입력: 9901
12
수 입력: 9999
36
수 입력: 9997
192
def count_ones(arr):
for i in range(len(arr)):
c = int(arr[i])
b = 1
cnt = 1
while True:
if b%c == 0:
print(cnt)
break
else:
b = b*10 + 1# c의 자리수를 계속해서 증가시킨다.
cnt += 1
if __name__ == '__main__':
arr = input().split()
count_ones(arr)
while True :
a = int(input("2나 5로 나눌수 없는 0~10000사이 숫자를 입력해주세요"))
if a >= 0 and a <= 10000 and a%2 != 0 and a%5 !=0 :
break
n=1
while True :
num = a*n
arr = str(num)
if len(arr) == arr.count("1") :
print("모든자리수가 1인 수 중 가장 작은수 :", arr)
print("몇자리수? :", len(str(arr)))
break
n +=1
_input = int(input("입력 : "))
_result = 0
count = 0
while not all([ _bool == '1' for _bool in str(_result)] ) :
for i in range(1,10) :
_input_int = int(str(_result)[:len(str(_result))-count])+ int(_input * i)
if str(_input_int)[-1] == '1' :
_result += int(_input * i) * ( 10**count)
count += 1
break
print(len(str(_result)))
// Rust
// 곱해서 1만 나오는 방법으로 접근하면 시간이 오래걸립니다. (1의 자리수 11, 37, 73, 99만 고려해도..)
// 1만 나오는 수를 나눈 나머지로 접근해야 빨리 풀 수 있습니다
fn ones(n: usize) -> u32 {
let mut l: u32 = 1;
let mut rem = 0;
loop {
rem += 10usize.pow(l-1) % n;
if rem % n == 0 {
return l;
}
l += 1;
}
}
n=9901
a=n
def ones(a):
return min([int(x)==1 for x in str(a)])
while True:
if ones(a) == 0:
a=a+n
if ones(a) ==1 : break
print(len(str(a)))
초보에서 중수가 된 것 같습니다.ㅎ
ans='1'
n=9901
while True:
if int(ans)%n!=0:
ans+='1'
else:
print(len(ans))
break
def one(n):
if n > 0 and n < 10000 and n % 2 != 0 and n % 5 != 0:
i = 1
while True:
num_digits = len(str(n * i))
compare_num_digits = 0
for num_digit in range(num_digits):
if str(n * i)[num_digit] == '1':
compare_num_digits += 1
i += 1
if num_digits == compare_num_digits:
print(num_digits)
break
else:
print("잘못된 입력입니다. 0부터 10000사이의 정수, 2 그리고 5로 나눠질 수 없는 정수를 입력하세요")
def Ones(n):
a = n
while str(n) != len(str(n)) * '1':
n += a
print(len(str(n)))
Ones(3)
Ones(7)
Ones(9901)
j = 0
result = 0
while True:
num = int(input("2나 5로 나눌 수 없는 0 이상 10,000 이하의 정수 입력하시오:"))
if num % 2 == 0 or num % 5 == 0 or num == 0:
print("다시 입력하시오")
else:
break
while True:
j += 1
result = num * j
if len(str(result)) == str(result).count('1'):
break
print(len(str(result)))
def onesMultiple(n):
su, r, p = 1, 1, 1
while r != 0:
su *= 10
r = (su +r)% n
p += 1
print(p)
onesMultiple(3)
onesMultiple(7)
onesMultiple(9997)
JAVA입니다.
package question4.ones;
public class Main {
public static void main(String[] args) {
int[] inputs = {3, 7, 9901};
int[] outputs = new int[inputs.length];
for (int i = 0; i < inputs.length; i++) {
long ones = 1;
while(true) {
if(ones%inputs[i] == 0) {
outputs[i] = Long.toString(ones).length();
break;
}
ones = nextOnes(ones);
}
}
for (int i : outputs) {
System.out.println(i);
}
}
static long nextOnes(long n) {
return 10*n+1;
}
}