Pandigital prime | Project Euler | Problem #41
URL to the problem page: https://projecteuler.net/problem=41
We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.
What is the largest n-digit pandigital prime that exists?
We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.
What is the largest n-digit pandigital prime that exists?
#include <iostream>
using namespace std;
long long primecontrol(long long a) {
long long i, counter = 0;
for (i = 2; i <= sqrt(a); i++) {
if (a % i == 0) {
counter++;
break;
}
}
if (counter == 0) {
return 1;
}
else {
return -1;
}
}
long long finddigits(long long a) {
long long counter = 1;
while (a >= 10) {
a /= 10;
counter++;
}
return counter;
}
long long power(long long a, long long b) {
long long result = 1;
for (int i = 0; i < b; i++) {
result = result * a;
}
return result;
}
int main()
{
long long i, j, a, counter, counter2, digitnumber;
long long digits[9];
for (i = 987654321; i > 0; i -= 2) {
for (j = 0; j < 9; j++) {
digits[j] = 0;
}
counter2 = 0;
digitnumber = finddigits(i);
for (j = digitnumber; j > 0; j--) {
digits[j - 1] = (i % power(10, j)) / (power(10, (j - 1)));
}
for (j = 1; j <= digitnumber; j++) {
counter = 0;
for (a = 0; a < digitnumber; a++) {
if (digits[a] == j) {
counter++;
}
}
if (counter != 1) {
counter2++;
break;
}
}
if (counter2 == 0) {
if (primecontrol(i) == 1) {
cout << "Largest n-digit pandigital prime is = " << i << endl;
break;
}
}
}
}
Comments
Post a Comment