95개의 풀이가 있습니다.
reduce 짱짱맨
from functools import reduce
def gcd(a, b):
if a < b: a, b = b, a
while b: a, b = b, a % b
return a
def lcm_range(a, b): return reduce(lambda x, y: x*y/gcd(x, y), range(a, b+1))
print(lcm_range(1, 20))
Swift입니다.
단순하게 20씩 증가하면서 그 수가 11부터 20까지 나누어지는지 검사했습니다. 11부터 20까지 나뉘면 역시 2부터 10까지 나뉘기 때문에 10이하는 생략했습니다.
20씩 증가를 해도 답을 찾지만, 20까지의 소수들의 곱, 즉 [1,2,3,5,7,11,13,17,19]의 곱인 9699690으로 증가를 시키면 단, 24번의 루핑으로 답을 찾을 수 있었습니다.
func findNumber() -> Int {
let dividers = Array(11...20)
var number = 0
while true {
number += 9699690 // number += 20
if dividers.reduce(true, {$0 && (number % $1 == 0)}) {
break
}
}
return number
}
print( findNumber() )
결과는...
232792560
1부터 20까지의 어떤 수로도 나누어지는 수는 1부터 20까지의 최소공배수입니다
이 수를 인수분해했을때
2의 지수는 4 (16)
3의 지수는 2 (9, 18)
나머지(5, 7, 11, 13, 17, 19)의 지수는 1입니다
따라서 2^4 * 3^2 * 5 * 7 * 11 * 13 * 17 * 19 = 232792560
public class qqq {
public static void main(String[] args) {
boolean k=true;
int n=1;
while(k) {
n++;
if (n%1==0&&n%2==0&&n%3==0&&n%4==0&&n%5==0&&n%6==0&&n%7==0&&n%8==0&&n%9==0&&n%10==0
&&n%11==0&&n%12==0&&n%13==0&&n%14==0&&n%15==0&&n%16==0&&n%17==0&&n%18==0&&n%19==0&&n%20==0){
k=false;
}
}
System.out.println(n);
}}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodingStudio161
{
class Program
{
static int start;
static int end;
static void Main(string[] args)
{
/*1부터 10까지의 어떤 수로도 나누어 떨어지는 가장 작은 수는 2520입니다.
* 그렇다면 1부터 20까지의 어떤 수로도 나누어 떨어지는 가장 작은 수는 얼마입니까?*/
Console.WriteLine("*** Coding Studio 169Q ***");
int test = 0;
Console.WriteLine("몇 부터 몇까지 나누어 떨어지는 수를 구하겠습니까??");
Console.WriteLine("시작 수 : ");
start = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("마지막 수 : ");
end = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("");
Console.WriteLine("{0} 부터 {1} 까지 모두 나누어 떨어지는 수를 구합니다.", start, end);
while (true)
{
test++;
if (Test(test))
{
Console.WriteLine("{0} 부터 {1} 까지 모두 나누어 떨어지는 수는 {2} 입니다.", start, end, test);
break;
}
}
}
static bool Test(int a)
{
for(int i = start; i <= end; i++)
{
if (a % i != 0)
{
return false;
}
}
return true;
}
}
}
#include "stdafx.h"
#include <iostream>
int main()
{
int cnt = 0, num = 0;
int i = 1;
while (1)
{
num++;
std::cout << num << "\n";
for (i = 1; i < 20; i++) if (num%i != 0) break;
if (i == 20) break;
}
std::cout << num << "은 1부터 20까지의 모든수로 나눠지는 수입니다.";
}
Ruby
gcd = ->a,b { a, b = b, a % b until b.zero?; a }
lcm = ->num { (1..num).reduce {|lcm, num| (lcm * num) / gcd[lcm, num]} }
Test
expect( gcd[4, 6] ).to eq 2
expect( gcd[6, 12] ).to eq 6
expect( lcm[10] ).to eq 2520
expect( lcm[20] ).to eq 232792560
#include <stdio.h>
int main()
{
int i = 0;
int j = 1;
while(j)
{
i++;
if(i%1==0&&i%2==0&&i%3==0&&i%4==0&&i%5==0&&i%6==0&&i%7==0&&i%8==0&&i%9==0&&i%10==0&&i%11==0&&i%12==0&&i%13==0&&i%14==0&&i%15==0&&i%16==0&&i%17==0&&i%18==0&&i%19==0&&i%20==0)
j = 0;
}
printf("%d\n", i);
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int num = 1;
int count = 0;
while (true)
{
num++;
for (int i = 1; i <= 20; i++)
{
if (num%i == 0)
{
count++;
}
}
if (count == 20)
break;
else
count = 0;
}
cout << "1부터 20까지의 수로 나누어 떨어지는 가장 작은수는>>" << num << "입니다." << endl;
}
public class re {
public static void main(String[] args) {
while (true)
{
num++;
for (int i = 1; i <= 20; i++)
{
if (num%i == 0)
{
count++;
}
}
if (count == 20)
break;
else
count = 0;
}
System.out.println(n);
}
def minvalue():
i = 0
while True:
i += 1
if (i % 1 == 0 and i % 2 ==0 and i % 3 == 0 and i % 4 == 0 and i % 5 == 0 and i % 6 == 0 and i % 7 == 0 and i % 8 == 0 and i % 9 == 0 and i % 10 == 0 and i % 11 == 0 and i % 12 == 0 and i % 13 == 0 and i % 14 == 0 and i % 15 == 0 and i % 16 == 0 and i % 17 == 0 and i % 18 == 0 and i % 19 == 0 and i % 20 == 0):
print(i)
break
%%time
minvalue()
232792560
Wall time: 1min 10s
소인수분해부터 최소공배수를 프로그래밍으로 돌려봤습니다. 파이썬
# soin 함수는 소인수분해를 해주는 함수
def soin(n):
list1 = []
while(n>1):
for i in range(2,n+1):
if n%i == 0:
list1.append(i)
n = n//i
break
return list1
# set을 사용해 모든 원소의 고유한 값을 구하고,
# list2를 사용해서는 전체 리스트를 반환 받는다.
set1 = set()
list2 = []
for i in range(2,20+1):
so = soin(i)
set1 = set1 | set(so)
list2.append(so)
# print(set1)
# print(list2)
# Output:
# {2, 3, 5, 7, 11, 13, 17, 19}
# [[2], [3], [2, 2], [5], [2, 3], [7], [2, 2, 2], [3, 3], [2, 5], [11], [2, 2, 3], [13], [2, 7], [3, 5], [2, 2, 2, 2], [17], [2, 3, 3], [19], [2, 2, 5]]
# list2의 count 함수를 사용해 모든 원소의 최대값을 찾고
# dict를 사용해 이를 정리한다.
dict1 = dict()
for i in set1:
dict1[i] = 0
for j in list2:
if dict1[i] < j.count(i):
dict1[i] = j.count(i)
# print(dict1)
#Output:
# {2: 4, 3: 2, 5: 1, 7: 1, 11: 1, 13: 1, 17: 1, 19: 1}
# 모든 소인수분해를 종합한 데이터를 연산한다.
result = 1
for i in dict1.keys():
result *= i ** dict1[i]
print(result)
#Output:
# 232792560
20 이하의 소수만 구해서 전부 곱하면 됩니다.
public class test {
public static void main(String[] args) {
int sum = 1;
for (int i = 2; i < 21; i++) {
boolean go = true;
for (int j = 2; j < i; j++)
if (i % j == 0)
go = false;
if (go)
sum *= i;
}
System.out.println(sum);
}
}
Python 3.6
단순 루프를 통해 배수판별을 할 경우 이 문제의 경우에는 2억번이 넘는 루프를 거쳐야 한다
최소공배수를 구할 리스트의 멤버중 소수 또는 소수의 제곱인 수들의 최소공배수를 기본으로 그 값의 배수중 결과값을 찾았다
루프를 최대한 줄이기 위해 break문을 적극 사용하였다
소인수 분해 하는 것이나 이거나 별반 차이 없을지도...
def LCmultiplesub(n): # 2이면 소수, 3이면 1, n, sqrt(n) 3개의 약수를 가진 수
count = 2
for i in range(int(n**0.5),1,-1):
if i**2 == n:
count = 3
continue
if not n%i: return False
return count
def LCmultiple(numlist):
r = 1
c_e = tuple(map(lambda i : i if LCmultiplesub(i) == 2 else int(i**0.5) if LCmultiplesub(i) == 3 else 1,numlist))
for i in c_e: r *= i
result = r
while 1:
for i in set(numlist) - set(c_e):
if result%i:
check = False
break
else: check = True
if check: break
result += r
return result
numlist = [x for x in range(1,21)]
print(numlist)
print('최소공배수: %d' % LCmultiple(numlist))
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
# 최소공배수: 232792560
using System;
using System.Collections.Generic;
using System.Linq;
namespace CD160
{
class Program
{
static int Scale = 20;
static IEnumerable<int> Divisor = Enumerable.Range(1, Scale);
static void Main(string[] args)
{
int num = Scale;
while (!IsDividable(num)) { num += Scale; }
Console.WriteLine(num); // 232792560
}
static bool IsDividable(int aNumber) => Divisor.All(element => aNumber % element == 0);
}
}
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
long answer = 1;
for(long i = 1; i < 20; i++)
{
answer = getMin(answer, i + 1);
System.out.println( i+":"+ answer);
}
}
public static long getMax(long a, long b)
{
while(a != 0 && b != 0)
{
long temp = b;
b = a%b;
a = temp;
}
return a;
}
public static long getMin(long a, long b)
{
long max = getMax(a, b);
long min = (a*b) / max;
return min;
}
}
public class Javatutorial {
public static long gcd(long a, long b) {
if (b == 0)
return a;
else
return gcd(b, a % b);
}
public static long lcm(long a, long b) {
return a * b / gcd(a, b);
}
public static void main(String[] args) {
long res = 1;
for (int i = 2; i <= 20; i++) {
res = lcm(res, i);
}
System.out.println(res);
}
}
public class Practice {
public static void main(String[] args) {
int x=1;
total : while(true) {
for(int i=1; i<=20; i++) {
if(x%i!=0) { //나눠지지 않으면 for문을 멈추고 x++를 실행
break; //i가 10이 되면 아래로 흘린다
}else if(i==20) { //i가 10이면 while문을 중지시킨다
break total;
}
}
x++; //숫자를 1씩 증가한다
}
System.out.println(x);
}//end main
}//end class
from functools import reduce
def func(x, y):
if x < y:
x, y = y, x
while y:
x, y = y, x % y
return x
def ran(x, y):
return reduce(lambda x, y: x*y/func(x, y), range(x, y+1))
print(ran(1, 20))
public class TEST13 {
public static void main(String[] args) {
System.out.println(divide(20));
}
public static long divide(int n) {
long value = 0L;
boolean isFound = false;
for (int i = n + 1; i < Integer.MAX_VALUE; i++) {
if (isFound) {
break;
}
for (int k = 1; k <= n; k++) {
if ((i % k) == 0) {
if (k == n) {
value = i;
isFound = true;
break;
}
}
else {
break;
}
}
}
return value;
}
}
import time
start = time.time()
print(start)
n = 0
con = 0
list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
while True:
n = n + 1
for i in list:
if n%list[i] != 0:
break
if list[i] == 20:
con = 1
break
if con == 1:
break
end = time.time()
start_end_time = end-start
print(end)
print('Elapsed %.03f' % start_end_time)
print('Min:'+str(n))
'''
1543985034.3480535
1543985239.389781
Elapsed 205.042
Min:232792560
'''
package pac;
import java.util.*;
public class franklin {
public static void main(String[] args)
{
int i=0,j=0,k=0;
while(true)
{
i++;
for(j=1;j<21;j++)
{
if(i%j==0)
{
k++;
}
}
if(k == 20)
break;
else
k = 0;
}
System.out.println(i);
}
}
맨처음에 일일이 if 문에다가 i%1==0 && i%2==0 했는데 일일이 한게 while 내부에 for문 돌리는 것보다 속도가 더 잘 나오는 느낌입니다...ㅠㅠ
%1~n사이의 어떠한 수로 나누어도 나누어떨어지는 최소의 수
n=input('수 입력: ');
i=1;
while true
count=0;
for j=1:n
k=rem(i,j);
if k==0
count=count+1;
end
end
i=i+1;
if count==n
break
else
continue
end
end
fprintf('%d\n',i-1);
public class Problem160 {
long GCD (long i, long j) {
long temp=0;
if(i<j) {
temp=j;
j=i;
i=temp;
}
do {
temp=i%j;
i=j;
j=temp;
}while(temp!=0);
return i;
} //최소공배수를 구하는 method
long LCM (long i, long j) {
long temp=GCD (i,j);
return i*j/temp;
} //최대공약수를 구하는 method
public static void main(String[] args) {
Problem160 problem = new Problem160();
long result=20;
for(long i=result-1;i>=1;i--) {
result = problem.LCM(result, i);
}
System.out.println(result);
}
}
namespace codingdojang__
{
class Program
{
static void Main(string[] args)
{
for (int i = 20; ; i += 20)
{
for (int e = 11; e <= 20; e++)
{
if (i % e != 0)
{
break;
}
if (e == 20 && i % e == 0)
{
Console.WriteLine(i);
Environment.Exit(0);
}
}
}
}
}
}
prime_number =[]
for i in range(2,21):
chk = True
for j in range(2,i):
if i%j == 0:
chk = False
break
if chk:
prime_number .append(i)
multiplication=1
for z in prime_number:
multiplication*=int(z)
answer=0
while True:
ti=0
answer = answer + multiplication
for i in range(1,21):
i=int(i)
if answer%i==0:
ti+=1
if ti==20:
print(answer)
quit()
소수를 구하는식도 첨부.. 어렵네요
def gcd(a,b):
if b==0:
return a
else:
return gcd(b, a%b)
def lcm(a,b):
return a*b//gcd(a,b)
mul=1
for i in range(1,51):
mul=lcm(mul,i)
print(mul)
#include <stdio.h>
#include <iostream>
using namespace std;
void main() {
int n = 1;
while (true)
{
int cnt = 0;
for (int i = 1; i <= 20; i++)
{
if (n % i == 0)
cnt++;
if (cnt == 20)
{
printf("%d", n);
exit(1);
}
}
n++;
}
}
11부터 20 까지의 최소공배수를 구하면 됩니다.
2의 지수가 있는수 - 12,14,16,18,20. 최대 - 16.(2^4)
3 - 12,15,18 최대 - 18.(3^2)
5 - 10,15,20. 최대 - 다.(5^1)
5 이후는 모두 지수가 1이니,
2^4 * 3^2 * 5 * 7 * 11 * 13 * 17 * 19 를 하면 됩니다.
--- 232,792,560
•Made by Highlander
def gcd(a, b):
if a < b:
return gcd(b, a)
if a % b == 0:
return b
return gcd(b, a % b)
def lcm(a, b):
g = gcd(a, b)
x = a // g
y = b // g
return g * x * y
from functools import reduce
def eu05():
result = reduce(lambda a, b: lcm(a, b), range(1, 21),1)
return result
answer = eu05()
print(answer)
def checkPrime(num):
if num != 1:
for i in range(2,num):
if num %i == 0:
return False
else:
return False
return True
def primeNum(num):
t = (x for x in range(2, num+1))
prime = []
for i in t:
if checkPrime(i):
prime.append(i)
return prime
# 암살자까마귀님 코드참고
ans=1
for i in primeNum(20):
while 1:
if i*i>20:
ans*=i
break
i*=i
print(ans)
num=2520
i=11
while True:
if num%i==0:
i +=1
if i==21:
break
else:
i=11
num +=20
print(num)
``````{.python}
num=2520
i=11
while True:
if num%i==0:
i +=1
if i==21:
break
else:
i=11
num +=20
print(num)
def Func1(n):
list_0 = []
while n > 1:
for i in range(2, n+1):
if n%i == 0:
list_0.append(i)
n = int(n/i)
break
return list_0
list_1 = []
set_1 = set()
dict_1 = dict()
for i in range(2, 21):
a = Func1(i)
list_1.append(a)
set_1 = set_1 | set(a)
for i in set_1:
dict_1[i] = 0
for j in list_1:
if dict_1[i] < j.count(i):
dict_1[i] = j.count(i)
result = 1
for i in dict_1.keys():
result *= i**dict_1[i]
print(result)
정말 무식하게 숫자 대입하는 것으로 풀었습니다...
value = [v for v in range(1,21)]
for i in range(21,10000000000):
count = 0
for j in value:
if i%j != 0:
break
else :
count +=1
if count == 20 :
print(i)
break
파이썬 얼마나 무식한 방법인지 돌리고 나서 알게 됨. 결과 나오는데 몇 분은 걸린 듯.
# the smallest number divided by any number between 1 and 20
x = 20
while True:
x += 1
cnt = 0
for i in range(2, 21):
if x % i != 0:
#x += 1
break
cnt += 1
if cnt == 19:
print(x)
break
print(x)
import java.util.*;
public class 어떤수로도나누어떨어지는가장작은수 {
public static void main(String[] args) {
int num = 0;
for(int i = 2521;; i++) {
int count = 0;
for(int j=1; j<21; j++) {
if(i%j!=0) {
break;
}
if(i%j==0) {
count+=1;
}
}
if(count==20) {
num=i;
break;
}
}
System.out.println(num);
}
}
파이썬
from functools import reduce
def gcd(x,y): # 최대공약수 구하는 함수
while y:
x,y=y,x%y
return x
def lcm(x,y): # 최소공배수 구하는 함수
lcm = x*y/gcd(x,y)
return lcm
range20=reduce(lambda x,y:lcm(x,y),range(1,21)) # reduce() 집계 함수로 1~20까지 곱한 후 최대공약수로 나누는 최소공배수 함수를 적용.
print(range20) #232792560
최대공약수, 최소공배수 개념적어놓은 블로그 입니다. 어설프게 설명 적어넣는것보단 위 사이트 가셔서 보시는게 좋을것 같습니다.
n, li = 20, [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
while True :
for i in li :
if n%i != 0 :
break
if i == 20 :
print(n)
break
n += 20
결과
232792560
int MinimumCommonMultiNum (int a)
{
int result = 0;
bool have_result_found = false;
while(have_result_found ==false)
{
result++;
for(int i = 1; i <=20 ; i++)
{
result % i == 0 ? 0: break;
i == 20 ? have_result_found = true, break: 0;
}
}
return result;
}
k=20
while True:
if k%1==0 and k%2==0 and k%3==0 and k%4==0 and k%5==0 and k%6==0 and k%7==0 and k%8==0 and k%9==0 and k%10==0 and k%11==0 and k%12==0 and k%13==0 and k%14==0 and k%15==0 and k%16==0 and k%17==0 and k%18==0 and k%19==0 and k%20==0:
print(k)
break
k+=20
# 232792560
N, Nmain, Ncheck = 2520, 0, True
while(Ncheck):
N += 20
for i in range(1,21):
Nmain += N%i
if Nmain == 0:
Ncheck = False
Nmain = 0
print(N)
파이썬 3입니다.
최소공배수를 구하는것 보다는 최대공약수를 구하는 것이 나을 것 같아서 최대공약수를 먼저 구하고 그것을 이용해서 최소공배수를 구했습니다
# 최소공배수 = 두 수의 곱 / 최대 공약수
def G(x, y): # 최대 공약수
if x % 2 == 0 and y % 2 == 0:
return 2 * G(x // 2, y // 2)
if min(x, y) == 1:
return 1
gcd = 1
for i in range(1, (max(x, y) - 2) // 4 + 1):
if (2 * i + 1) > min(x, y):
break
if x % (2 * i + 1) == 0 and y % (2 * i + 1) == 0:
gcd = 2 * i + 1
return gcd
def L(x, y): # 최소 공배수
return (x * y) // G(x, y)
lcm = 1
for n in range(2, 21):
lcm = L(n, lcm)
print('답은 {}이다'.format(lcm))
a = 0
while True:
a += 1
if a % 1 == 0 and a % 2 == 0 and a % 3 == 0 and a % 4 == 0 and a % 5 == 0 and a % 7 == 0 and a % 8 == 0 and a % 9 == 0 and a % 10 == 0 and a % 11 == 0 and a % 12 == 0 and a % 13 == 0 and a % 14 == 0 and a % 15 == 0 and a % 16 == 0 and a % 17 == 0 and a % 18 == 0 and a % 19 == 0 and a %20 ==0:
break
print(a)
n = 1 while True: cnt = 0 for i in range(1,21): if n % i !=0: cnt+=1
n+=1 if cnt==0:
print(n) break
#cheer님의 코딩을 복사 붙여넣기 했습니다.(원래 cnt가 아니라 b였는데, b는 저로서는 count라고 생각해서 cnt라고 적었습니다.)
n=0
while 1:
x=0
n+=1
for i in range(1,21):
if n%i==0:
x+=1
pass
else:
break
if x==20:
break
print(n)
왜이리 오래걸리나 해서 print(n) 앞에 탭 넣어봤더니 알겠더라고요
def minmul(n):
mid=1
Mid=[]
for i in range(1, n+1):
mid*=i
for i in range(1, n):
Mid.append(i)
for i in range(1, mid):
MID=[]
for j in Mid:
MID.append((n*i)%j)
if set(MID)=={0}:
print(n*i)
break
print(minmul(20))
문제의 조건을 만족하는 수가 20!이하라는 것을 이용했습니다.
num=0
while (1):
num=num+(2357111317*19)
i=0
while (i<21):
i=i+1
if (num%i!=0):
break
if (i>20):
break
print (num)
public class Q159 {
public static void main(String[] args) {
int temp = 0;
for (int i = 1;; i++) {
if (temp == 0) {
for (int j = 1; j < 21; j++) {
if (i % j == 0) {
temp = i;
} else {
temp = 0;
j = 0;
break;
}
}
} else {
System.out.println(temp);
break;
}
}
}
}
from functools import reduce
import math
def ran(x, y):
return reduce(lambda x, y: x*y//math.gcd(x,y), range(x, y+1))
print(ran(1, 20))
public class print {
public static void main(String[] args){
int result = 1;
// a와 b를 각각 나눠지는 수, 나누는 수라고 할 떄
// a가 b로 완전히 나누어 떨어지게 하려면 다음의 계산을 진행하면 된다.
// a * (b/최대공약수)
for (int k = 1; k <= 20; k +=1 ){
result = result * (k/maxcom(result, k));
System.out.println(result);
}
}
public static int maxcom(int a, int b){
// 유클리드 호제법을 이용하여 최대공약수 구함
int max = Math.max(a, b);
int min = Math.min(a, b);
int R = max % min;
if(R == 0){
return min;
}
return maxcom(min, R);
}
}
def div_det(n): #n의 약수 찾아서 약수 리스트를 반환
div=[]
for i in range(1,n+1):
if n%i == 0:
div.append(i)
return div
def prime_det(n): # 1~n 범위중에 소수들을 찾아서 소수리스트를 반환
prime =[]
for i in range(1,n+1):
if len(div_det(i)) == 2:
prime.append(i)
return prime
def factorize(n):#n의 소인수 리스트를 반환
factors =[]
cnt=0
while True:
if n % prime_det(n)[cnt] == 0:
factors.append(prime_det(n)[cnt])
n = n//prime_det(n)[cnt]
if n == 1:
break
elif n % prime_det(n)[cnt] != 0:
cnt+=1
return factors
def cnt_element(key,lst):# key값이 list에 몇개나 존재하는지. ex)[4,3,2,1,1] => key=1 일때
# cnt=2 를 반환
cnt=0
for num in lst:
if key == num:
cnt+=1
return cnt
def union(lst): # 합집합(중복된 요소 삭제+오름차순 정렬)
set(lst)
return list(set(lst))
def lcm_maker(list_a, list_b): #최소공배수 생성
key=0
lcm=1
for num in union(list_a):
temp=0
for i in range(len(list_a)):
if num == list_a[i]: #같은 값의 factor를 찾았을경우
if list_b[i]>=temp: #해당 factor의 개수가 가장 많은 갯수를
temp = list_b[i] #temp에 저장하고
key=i #해당 인덱스도 저장한다
lcm=lcm*(list_a[key]**temp)
return lcm
#num_lst = [4,6]
num_lst = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
sort_num_lst = sorted(num_lst)
factor_lst_lst=[]
a=[]
b=[]
if sort_num_lst[0] == 1:
factor_lst_lst.append([1])
x=1 # factorize() 함수에 매개변수 값이 1이들어가면 out of range발생
#그래서 num_lst의 첫번째 값이 1 일경우엔 강제로 1을 추가하고
#for문은 index=1부터 시작
else : x=0
for i in range(x,len(sort_num_lst)):
factor_lst_lst.append(factorize(sort_num_lst[i]))
# 입력 숫자 각각의 소인수 리스트(리스트 안의 리스트 형식)
for i in range(len(factor_lst_lst)):
for j in range(len(union(factor_lst_lst[i]))):
a.append(union(factor_lst_lst[i])[j])
#소인수분해 리스트를 하나로 합친것
for i in range(len(factor_lst_lst)):#
for j in range(len(union(factor_lst_lst[i]))):
b.append((cnt_element(union(factor_lst_lst[i])[j],factor_lst_lst[i])))
#각 소인수가 몇개씩 있는지
print(factor_lst_lst)
print("\n합칩합 : ",union(a))
print("\na :",a)
print("\nb :",b)
print("\n최소공배수 : ",lcm_maker(a,b))
파이썬 왕초보라서 스파게티처럼 꼬여있습니다. 코드 짜는대 대략 9시간 걸렸네요;;
package test;
public class Test{
public static void main(String[] args) {
int num=20;
int count = 0;
boolean result = false; //num은 나눠지는 값, i는 나누는 값, count는 나누어 떨어지는 횟수
while(result != true) {
for(int i = 1; i <=20 ; i++) { //i를 1~20까지 나눔
if(num % i == 0)
count++; //나누어 떨어질때마다 count 추가
}
if(count != 20) {//1~20중 하나라도 안 나누어 떨어질때
num++; //다음 숫자
count = 0; //count 초기화
}
else if(count == 20)//1~20 어떤 수로도 나누어 떨어질 때
result = true; //result true로 while문 종료
}
System.out.println(num);
}
}
namespace _60일차_9월30일
{
class MainApp
{
static void Main(string[] args)
{
//1부터 20 사이의 어떤 수로도 나누어 떨어지는 가장 작은 수
int cnt = 0;
int data = 0;
int result = 20;
while (true)
{
result++;
for (int j = 1; j <= 20; j++)
{
if (result % j == 0)
cnt++;
else break;
}
data = result;
if (cnt == 20)
break;
cnt = 0;
}
Console.WriteLine($"Result = {data}");
}
}
}
class getTheNumber:
def __init__(self):
self.num = 0
def calToNum(self,n):
j = n
while True:
k = True
for i in range(1,n+1):
if j%i != 0:
k = False
if k == True:
self.num = j
break
j += n
print (self.num)
a = getTheNumber()
a.calToNum(10)
a.calToNum(20)
def sosu(num):
result = []
for i in range(1,int(num)+1):
if int(num) % i == 0:
result.append(i)
if len(set(result)) == 2:
return True
def insu(num):
temp = int(num)
result = []
result2 = []
while temp != 1:
for i in range(2,temp+1):
if temp % i == 0 and sosu(i):
result.append(i)
temp = temp // i
result.sort()
result1 = list(set(result))
result1.sort()
for aa in result1:
count = 0
for bb in result:
if bb == aa:
count += 1
result2.append(count)
return [result1, result2]
num = int(input('num? : '))
ins = []
full = {}
mult = 1
for i in range(1,num+1):
for aa in insu(i)[0]:
if aa not in ins:
ins.append(aa)
full[aa] = insu(i)[1][insu(i)[0].index(aa)]
if insu(i)[1][insu(i)[0].index(aa)] > full[aa]:
full[aa] = insu(i)[1][insu(i)[0].index(aa)]
for aa in full.keys():
mult = mult*(aa**full[aa])
print(mult)
파이썬입니다. number increment 는 그냥 간단하게 제일 큰수 19, 20 곱한값으로 지정해줬습니다. 계산시간은 1.8초 걸리네요.
number = 380
while True:
count = 0
for divisor in range(1, 21):
if number % divisor == 0:
count += 1
if count == 20:
print(number)
break
else:
number += 380
continue
a=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
number=1
while True:
for i in a:
if number%i!=0:
break
if i==20:
print(number)
break
else:
number+=1
def gcd(a,b):
if(b == 0): return a
if(a < b): a,b = b,a
r = a % b
a = b
b = r
return gcd(a , b)
mul = 1
for i in range(2,21):
g = gcd(mul,i)
lcm = (mul*i)/g
mul = lcm
print(mul)
문제를 잘 보니 최소공배수를 구하는 문제네요.
def function(n):
data = [k for k in range(2,n+1)]
result ={}
for num in data:
for i in range(2,num+1):
count =0
while True:
if num%i==0:
count+=1
num/=i
else :
if str(i) not in result.keys() or count>result[str(i)]:
result[str(i)] = count
break
if num==1:
break
x = 1
for i in result.keys():
x*=int(i)**result[str(i)]
return x
i = 1
a = 1
while True:
if a == 21:
break
elif i % a == 0:
a += 1
elif i % a != 0:
i += 1
a = 1
print(i)
232792560 답은 나오는데 시간이 오래걸리네요..
from functools import reduce
def gcd(a,b):
if b==0:
return a
else:
return gcd(b, a%b)
reduce(lambda x,y:x*y/gcd(x,y),range(1,21))
왕초보입니다. sieve(n)은 부스트코스-처음 배우는 프로그래밍 w파이썬의 자료를 참고했습니다.
#강의자료 참고
def sieve(n):
candidates = list(range(2, n))
i = 0
while i < len(candidates):
prime = candidates[i]
j = i + 1
while j < len(candidates):
if candidates[j] % prime ==0:
candidates.pop(j)
else:
j += 1
i += 1
return candidates
def smallest_multiple(n):
candidates = sieve(n+1)
multiple = 1
for i in range(len(candidates)):
prime = candidates[i]
power = 1
while prime ** (power+1) < n:
power += 1
else:
multiple = multiple * ((candidates[i]) ** power)
return multiple
def insu(n):
li = []
while(n>1):
for k in range(2,n+1):
if n%k == 0:
li.append(k)
n = n//k
break
return li
li1 = []
li2 = []
for i in range(2,21):
li1.append(insu(i))
li2 += insu(i)
set1 = set(li2)
dic1 = {}
for i in set1:
count_list = []
for k in li1:
count_list.append(k.count(i))
dic1[i] = max(count_list)
num = 1
for i,j in dic1.items():
num *= i**j
print(num)
```{.python} lst = range(1, 11)
num = 2 result = None
while True: count = 0 for i in lst: if num % i == 0: count += 1 else: break if count == 10: result = num break num += 1
goal = int(input('>>> '))
result = 1
result_list = [1]
for num in range(1, goal+1):
target = num
for i in result_list:
a, b = divmod(target, i)
if not b:
target = a
# print('target : ', target)
result *= target
result_list.append(target)
# print(result)
print(result)
# print(result_list)
간단히 암산으로 생각해봤을 때, 1부터 시작해서 10까지 최소의 수를 곱해보면 ..
1 - 2 - 3 - 2(앞에 2가 하나 있으므로) - 5 - 1(2,3이 하나씩 있으므로) - 7 - 2(2가 2개뿐임) - 3 - 1
이렇게 2520을 구할 수 있다. 이 수의 배열을 result_list에 계속 갱신시켜주고 이 리스트의 값으로만 나누기를 진행한다.
for j in range(1, 232792561, -1):
for i in range(1,21):
if j%i!=0:
break
if i==20:
print(j)
break
else:
pass
# 정답 안나오네 1개월 뒤 보자
x = 20
while True:
found = True
for i in range(19,1,-1):
if (x%i)!=0:
found = False
break
if found:
break
x += 20
print(x)
정답은 232792560
#codingdojing_divideBy1to20_re
import time
# 최대수인 20씩 증가시켜서 약분이 되는지 확인.
# 미리 정해져있다면, 소수들의 곱부터 시작.
startN = 2*3*5*7*11*13*17*19*20
while True:
for i in range(11,21):
if startN % i == 0:
pass
else:
startN += 20
break
if i == 20:
break
print(startN)
#################### 풀이 참고 다른 방식, recursive function
from functools import reduce
def GCD(a,b):
if a < b: a, b = b, a
if a%b == 0: return b
else: return GCD(b, a%b)
print(int(reduce(lambda a,b: a*b/(GCD(a,b)), range(1,21))))
다른 분들의 풀이를 참고하였습니다.
python 3.9.6입니다.
import math
for num in range(2520*11*13*17*19, math.factorial(20), 11*13*17*19):
status = True
for test in range(11, 21):
if num % test: status = False; break
if status: print(num); break
실행 결과: 232792560
파이썬 3.8.10으로 작성되었습니다. 결과값은 232792560이 나왔습니다. 딕셔너리를 이용하여 나누어주고, 몫이 더 큰 경우 대체했습니다. 이후 나머지를 다시 재귀시켜 각 값들을 소인수분해 하였습니다.
def factor(n):
factors = {2: 0, 3: 0, 5: 0, 7: 0, 11: 0, 13: 0, 17: 0, 19: 0}
for p in factors.keys():
if p <= n:
share, remained = divmod(n, p)
if remained == 0:
factors[p] += 1
while share >= p and remained == 0:
share, remained = divmod(share, p)
if remained == 0:
factors[p] += 1
else:
pass
else:
break
return factors
def main():
answer = 1
prime_number = {2: 0, 3: 0, 5: 0, 7: 0, 11: 0, 13: 0, 17: 0, 19: 0}
for i in range(2, 21):
factor_i = factor(i)
print(i, factor_i)
for key in prime_number:
if factor_i[key] > prime_number[key]:
prime_number[key] = factor_i[key]
for key in prime_number:
if prime_number[key]:
answer *= (key**prime_number[key])
print(answer)
if __name__ == '__main__':
main()
lastNumber = 20
i = lastNumber
while True:
t = 0
i += 1
for n in range(1, lastNumber+1):
if i%n == 0:
t += 1
else:
break
if t == lastNumber:
break
print(i)
i=1
while True:
list=[]
for k in range(1,21):
if i%k==0: list.append(k)
if len(list)==20:
print(i)
break
else:
del list[:]
i=i+1
num=20
result=0
while not result:
for i in range(1,21):
if num%i != 0:
break
elif i==20:
result=num
break
num+=2
print(result)
A, B, C 의 최소 공배수는 A, B의 최소 공배수를 먼저 구하고 그 수와 C의 최소 공배수를 구하는 것으로 구할 수 있습니다. 즉, lcm 을 1...20 범위에서 폴딩하면 됩니다.
from functools import reduce
def gcd(a, b):
if a < b:
return gcd(b, a)
if b == 0:
return a
return gcd(b, a % b)
def lcm(a, b):
g = gcd(a, b)
return a // g * b
print(reduce(lambda x, y: lcm(x, y), i + 1 for i in range(20)))
static void div(int x) {
long n = 19399380, m = 2;
for (int i = 2; i <= x; i++) {
boolean isN = true;
for (int j = 2; j < i; j++) {
if (i % j == 0)
isN = false;
}
if (isN) {
m *= i;
}
}
while (true) {
boolean is = true;
for (int i = 1; i <= x; i++) {
if (n % i != 0) {
is = false;
n += m;
break;
}
}
if (is) {
System.out.println(n);
break;
}
}
}
public static void main(String[] args) {
div(20);
}
Li = []
n=20
while len(Li) == 0:
if int(max([n % x for x in range(1,20)])) == 0:
Li.append(n)
n = n+20
print(Li)
각 수를 소인수 분해(소수:승수 형식으로 HashMap에 저장)해서, 전체 수의 최소공배수를 찾는 알고리즘
// Rust use std::collections::HashMap; fn main() {
let limit = 20;
let primes = prime_numbers(limit).unwrap();
let mut map: HashMap<u32, u32> = HashMap::new();
for n in 2..=limit {
// for each n : factorization in prime factors
let mut m = n;
let mut map_t: HashMap<u32, u32> = HashMap::new();
for p in &primes {
if *p > m { break; }
while m % p == 0 {
let count = map_t.entry(*p).or_default();
*count += 1;
m /= p;
}
}
for (k, v) in map_t {
let count = map.entry(k).or_default();
if v > *count { *count = v; }
}
}
let total = map.iter().fold(1, |prod, (k, &v)| prod * k.pow(v));
println!("{:?} : {}", map, total);
}
fn prime_numbers(limit: u32) -> Option
let mut vec = vec![];
if limit >= 2 { vec.push(2); }
else {return None;}
for n in 3..=limit {
if (2..n-1).all(|i| n % i != 0) {
vec.push(n);
}
}
Some(vec)
}
package com.algorithm.algorithmpractice.dojang;
public class Div1To20 {
public static void main(String[] args) {
int k = 0;
int dx = 20;
while (true){
k+=dx;
boolean flag = true;
for(int i = 1; i <= 20; i++){
if(k % i != 0){
flag = false;
break;
}
}
if(flag){
break;
}
}
System.out.println(k);
}
}
최대공약수 공배수 생각안나서 무식하게 반복문 돌림;;
def gcd(a,b):
r = a % b
if r == 0: return b
elif b == 0: return a
else: return(gcd(b,r))
lcm = 1
for i in range(1,21):
lcm = (lcm * i) // gcd(lcm,i)
print(lcm)
파이썬입니다.
import math
math.lcm(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20)
232792560
result = 20
while True:
if result % 20 == 0 and result % 19 == 0 and result % 18 == 0 and result % 17 == 0 and result % 16 == 0 and result % 15 == 0 and result % 14 == 0 and result % 13 == 0 and result % 12 == 0 and result % 11 == 0 and result % 9 == 0 and result % 8 == 0 and result % 7 == 0 and result % 6 == 0 and result % 3 == 0:
print(result)
break
else:
result += 20
232792560
import time
start_time = time.time()
n = 1
while True:
b = 0
for i in range(1,21):
if n % i !=0:
b+=1
n+=1
if b==0:
print(n)
print("--- %s seconds ---" % (time.time() - start_time))
break
def gcd(a,b):
while b>0 :
if a < b:
a, b = b, a
a,b = b, a % b
return a
def lcm(a,b):
return a*b/gcd(a,b)
reduce(lambda x, y: x*y/gcd(x, y), range(1, 21))
public class DivNoNumber {
public static void main(String[] args) {
int cnt = 0;
int rs = 0;
while (true) {
cnt++;
rs = 0;
for (int i = 1; i < 21; i++) {
if (cnt % i == 0) {
rs++;
}
}
if (rs == 20) {
break;
}
}
System.out.println(cnt);
}
}
python
def find_num():
num = 1
while True:
for i in range(1,21):
if num % i == 0: #i로 나누어 떨어지면 continue
if i == 20: #20까지 나누어도 나누어 떨어지면 return
return num
continue
else:
break
num += 1
print(find_num())
public class Main {
public static void main(String[] args) {
boolean k=true;
int num = 0,count=0;
while(k){
num++;
for(int i=1;i<=20;i++) {
if (num % i == 0) {
count++;
}
} if (count == 20)
break;
else
count = 0;
}
System.out.println(num);
}
}
m = 0
def gcd(x,y):
while y != 0:
x,y = y, x % y
return x
def lcf(n):
m = 1
for i in range(1,n+1):
g = gcd(m,i)
m = (m * i) // g
return m
n = int(input("Input Range:"))
print(lcf(n))
def rangeLCM(b):
lst = [n for n in range(1, b+1)]
lcm = 1
for i in range(1, len(lst)):
lcm *= lst[i]
for j in range(i+1, len(lst)):
if lst[j] % lst[i] == 0:
lst[j] //= lst[i]
return lcm
print(rangeLCM(10))
print(rangeLCM(20))