문제 : https://www.acmicpc.net/problem/21919

#include<iostream>
using namespace std;
bool isPrime(int a) {
if(a==1) {
return false;
}
for(int i = 2; i < a; i++) {
if(a % i == 0) {
return false;
}
}
return true;
}
long long gcd(long a, long long b) {
if(a % b == 0) {
return b;
}
return gcd(b, a % b);
}
long long lcd(long long a, long long b) {
return a * b / gcd(a,b);
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
long long n,number;
long long total = 1;
cin >> n;
for(long long i = 0; i < n; i++) {
cin >> number;
if(isPrime(number)) {
total = lcd(total, number);
}
}
if(total==1) {
cout << -1 << "\n";
}
else{
cout << total << endl;
}
}
#include<iostream>
#include<cmath>
using namespace std;
bool isPrime(long long a) { // 에라토스테네스의 체 사용
if(a < 2) {
return false;
}
for(int i = 2; i * i<= a; i++) {
if(a % i == 0) {
return false;
}
}
return true;
}
long long gcd(long a, long long b) {
if(a % b == 0) {
return b;
}
return gcd(b, a % b);
}
long long lcd(long long a, long long b) {
return a * b / gcd(a,b);
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
long long n,number;
long long total = 1;
cin >> n;
for(long long i = 0; i < n; i++) {
cin >> number;
if(isPrime(number)) {
total = lcd(total, number);
}
}
if(total==1) {
cout << -1 << "\n";
}
else{
cout << total << endl;
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
private static boolean isPrime(int n) {
if(n < 2) return false;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) return false;
}
return true;
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
boolean[] bool = new boolean[1000001];
long result = 1;
String[] line = br.readLine().split(" ");
for (int i = 0; i < N; i++) {
int num = Integer.parseInt(line[i]);
if (isPrime(num) && !bool[num]) {
result *= num;
bool[num] = true;
}
}
if (result == 1)
System.out.println(-1);
else
System.out.println(result);
}
}
참고블로그 : https://llee-chan.tistory.com/9