2018年7月23日 星期一

itsa [C_AR08-易]找出數字字串中的最大質數

1.長度1需與2以上分開算
2.把字元轉成整數(要注意位數問題)

#include<iostream>
#include<string>
using namespace std;

int main()
{
int num = 0, l = 0, prime = 0, check = 0;
string s;
getline(cin, s);
if (s.length() >= 2)
{
for (int k = s.length(); k >= 2; k--)
{
for (int i = 0; i <= s.length() - k; i++)
{
num = 0;
check = 0;
for (int j = i; j < i + k; j++)
{
l = 1;
for (int x = j - i + 1; x < k; x++)
l *= 10;
num += (s[j] - '0') * l;
}
for (int j = 2; j * j <= num; j++)
{
if (j % 2 == 0 && j > 2)
continue;
if (num % j == 0)
{
check = 1;
break;
}
}
if (check == 0)
{
if (num > prime)
prime = num;
}
}
}
}
for (int i = 0; i < s.length(); i++)
{
check = 0;
num = s[i] - '0';
for (int j = 2; j < num; j++)
{
if (num % j == 0)
{
check = 1;
break;
}
}
if (check == 0)
{
if (num > prime)
prime = num;
}
}
if (prime == 0)
cout << "No prime found" << endl;
else
cout << prime << endl;
return 0;
}

沒有留言:

張貼留言