HDU 4548 美素數 素數題解,hdu4548

來源:互聯網
上載者:User

HDU 4548 美素數 素數題解,hdu4548

本題就是可以直接打表的,判斷是否可以打表也需要技巧的:

1 判斷最大的數值為1000000,百萬以下的數打表都是可以的

2 可以線性預先處理好,使用素數篩子法是可以接近線性預先處理的。

故此可以打表了。


需要熟悉的基本知識點:

1 素數篩子法 - 一兩分鐘之內寫出代碼

2 一般素數判斷法,因為位元相加之後的數值非常小,故此一般素數判斷就可以了,如果寫個primality test 演算法會大材小用了。

3 然後是帶點動態規劃法的思想把前面的美素數疊加起來,方便尋找。


算是基礎題目了,也是有人說的水題,我還是喜歡叫基礎題吧。

難在於判斷好,並運用好這些基礎知識,簡單優雅地解決,寫出代碼。

#include <stdio.h>#include <string.h>const int MAX_N = 1000001;bool isPrime(int n){if (n == 2) return true;for (int r = 2; r * r <= n; r++){if (n % r == 0) return false;}return true;}bool isMeiPrime(int n){int d = 0;while (n){d += n % 10;n /= 10;}return isPrime(d);}int primeNums[MAX_N];bool primes[MAX_N];void seive(){memset(primes, 0, MAX_N * sizeof(bool));for (int i = 2; i < MAX_N; i++){if (!primes[i]){for (int j = i << 1; j < MAX_N; j += i){primes[j] = true;}}}primeNums[0] = 0, primeNums[1] = 0;for (int i = 2; i < MAX_N; i++){if (!primes[i] && isMeiPrime(i)) primeNums[i] = primeNums[i-1] + 1;else primeNums[i] = primeNums[i-1];}}int main(){seive();int T, a, b;scanf("%d", &T);for (int t = 1; t <= T; t++){scanf("%d %d", &a, &b);printf("Case #%d: %d\n", t, primeNums[b] - primeNums[a-1]);}return 0;}




麻煩幫忙做下列vb題:1編寫一個判斷素數的函數;並在選項按鈕的單擊事件程序中,用inputbox輸入資料,再調

function isprime(m as integer)as boolean
dim i as integer
isprime=true
for i=2 to sqr(m)
if m mod i=-0 then
isprime=false
exit for
__end if ____
_next i_____
end function
private sub command1_click()
dim n as integer
n=__inputbox("請輸入n的值")_
if __isprime(n)_then
print n;"是素數"
else
print n ; "不是素數" ' 請自己完善這一段內容
end if
end sub
2. open app.path & “\a2.txt” for input as #1
do while not eof(1)
lineinput #1,a
str1=str1 &a
loop
open app.path & "a1.txt " for append as #2
print #2,str1
close
 
教編程,題目要在C++中1000以內的素數

#include <iostream.h>
void main()
{
int a,i,leap;
cout<<"1000以內的素數有:";
for(a=1;a<=1000;a++)
{
leap=1;//在每次重新判斷一個數是否素數的時候leap要重設為1
for(i=2;i<a;i++)
if(a%i==0) leap=0;
if(leap) cout<<a<<",";
}
}
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.