南陽ACM24-素數距離問題,南陽acm24-素數

來源:互聯網
上載者:User

南陽ACM24-素數距離問題,南陽acm24-素數
/*
素數距離問題
時間限制:3000 ms  |  記憶體限制:65535 KB
難度:2
描述
現在給出你一些數,要求你寫出一個程式,輸出這些整數相鄰最近的素數,並輸出其相距長度。如果左右
有等距離長度素數,則輸出左側的值及相應距離。
如果輸入的整數本身就是素數,則輸出該素數本身,距離輸出0
輸入
第一行給出測試資料群組數N(0<N<=10000)
接下來的N行每行有一個整數M(0<M<1000000),
輸出
每行輸出兩個整數 A B.
其中A表示離相應測試資料最近的素數,B表示其間的距離。
範例輸入
3
6
8
10
範例輸出
5 1
7 1
11 1
*/
//呵呵 ,用c語言寫的,

#include <stdio.h>
#include <math.h>


int isPrime(int n);


int main()
{
int i, n, num, temp1 = 0, temp2 = -1, flag = 0;
/* while(1)
{
scanf("%d", &n);


if (isPrime(n))
{
printf("is Prime\n", n);
}
else
{
printf("no\n");
}

}
*/

scanf("%d", &n);
while (n--)
{
scanf("%d", &num);
if (num == 1)
{
printf("2 1\n");
continue;
}


for (i = 0; i < num; ++i)
{
flag++;
temp1 = num + i*temp2;
// printf("temp = %d %d\n", temp1, temp2);
temp2 = temp2 * (-1);
if ((temp1>2 && temp1%10%2==0) || (temp1>3 && temp1%3 == 0) || (temp1>5 && temp1%5==0))
{
if (flag % 2 != 0)
{
--i;
}
continue;
}
else
{
if (isPrime(temp1))
{
break;
}
}


if (flag % 2 != 0)
{
--i;
}
}

if (temp1 > num)
{
if (isPrime(num-(temp1-num)))
{
printf("%d %d\n", 2*num-temp1, temp1-num);
}
else
{
printf("%d %d\n", temp1, temp1-num);
}
}
else if (temp1 < num)
{
printf("%d %d\n", temp1, num-temp1);


}
else if (temp1 == num)
{
printf("%d 0\n", num);
}
}


return 0;
}


int isPrime(int n)
{
int i = 2, a; 


a = sqrt(n) + 1;
// printf("a = %d  %lf\n", a, sqrt(3.0));
if (n == 2)
{
return 1;
}


for (i = 2; i <= a; ++i)
{
if (n % i == 0)
{

return 0;
}
}

return 1;

}


作者:http://blog.csdn.net/lp310018931


南陽理工oj素數距離問題,了我的逾時了

其他地方可改的不大 素數打表用素數篩

不知道素數篩的話 自己搜一下
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.