Quantcast
Channel: YGC » c++
Viewing all articles
Browse latest Browse all 18

project euler - problem 60

$
0
0

The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four primes with this property.

Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime.

把质数当成节点,如果两数互相连接后仍为质数,则连一边,那么这个问题就转化成为在图中找出大小为k的完全子图。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include<iostream>
#include<cmath>
#include<vector>
#include<fstream>
using namespace std;
 
bool is_prime(int n);
int concatNum(int a, int b);
 
const int N=10000;
 
int main() {
  ofstream out;
  out.open("p60.txt");
  vector<int> primes;
  primes.push_back(2);
  for (int i = 3; i < N; i+=2) {
    if (is_prime(i))
      primes.push_back(i);
  }
 
  for(int i=0; i<primes.size(); i++) {
    for (int j=0; j<i; j++) {
      if (is_prime(concatNum(primes[i], primes[j])) &&
	  is_prime(concatNum(primes[j], primes[i])) ) {
	out << primes[i] << "," << primes[j] << endl;
      }
    }
  }
  return 0;
}
 
bool is_prime(int n) {
  if ( n == 2)
    return true;
  if (n < 2)
    return false;
  if ( ! (n % 2) )
    return false;
  for (int i=3; i<=sqrt(n); i+=2) {
    if (n % i == 0)
      return false;
  }
  return true;
}
 
int concatNum(int a, int b) {
  int res = a * pow((double) 10, (int) log10(b) +1) + b;
  return res;
}

先生成边列表文件,再用igraph包,找出完全子图。

?View Code RSPLUS
1
2
3
4
5
6
require(igraph)
p <- read.csv("p60.txt", header=F)
g <- graph.data.frame(p, directed=FALSE)
subg <- cliques(g, min=5, max=5)
res <- sapply(subg, function(i) as.numeric(V(g)$name[i]))
min(colSums(res))

Related Posts


Viewing all articles
Browse latest Browse all 18