史萊姆論壇

史萊姆論壇 (http://forum.slime.com.tw/)
-   程式語言討論區 (http://forum.slime.com.tw/f76.html)
-   -   請問該如何用C寫呢?? (http://forum.slime.com.tw/thread219893.html)

rang0419 2007-11-09 05:18 PM

請問該如何用C寫呢??
 
An integer is said to be prime if it is divisible by only 1 and itself. For example, 2, 3, 5, and 7 are prime, but 4, 6, 8 and 9 are not.

1. Write a function that receives a number from the main function and determines if the number is prime.

2.Write the main function that
(a.)reads an integer n and uses the above function to determine and print all the prime numbers between 1 and n.

(b.)calulates the sum of all prime numbers between 1 and n.
A possibe run may look like:

Enter the number: 10
The prime numbers between 1 and 10 are:
2
3
5
7
The sum is 17.
Enter the number: 50
The prime numbers between 1 and 100 are:
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
The sum is 328.


可以參考一下嗎..........

joebin 2007-11-10 11:31 PM

語法:

#include<iostream>
using namespace std;
int main(){
  int s=0,n,m,i;  //s表總合,n表輸入的數字,m表要找的質數
  cout <<"please put in a num";
  cin >>n;
  if(n==1) cout <<"The sum is 0."<<endl;
  else{
    for(m=2;m<=n;m++)  //m由2到n
      for(i=2;i<=m;i++){
        if(m%i==0&&i!=m) break;  //當m不為質數時跳出
            if(i==m){
          cout <<m<<endl;  //m為質數,s+m=s
          s+=m;
        }
      }
  }
  cout <<"The sum is "<<s<<"."<<endl;
  system("pause");
  return 0;
}

還有The prime numbers between 1 and 100 are

這句有誤,應該是The prime numbers between 1 and 50 are

rang0419 2007-11-11 12:50 PM

非常感謝你的解答喔!!

很詳細又有註解~~~:on_82:

我現在就來試試看..........

感謝捏 有問題我再問你!!

rang0419 2007-11-11 01:01 PM

還有錯誤喔 不會吧 囧........

joebin 2007-11-11 02:58 PM

你看一下他題目要求的輸出方式

這邏輯應該無誤才對.......


所有時間均為台北時間。現在的時間是 09:26 PM

Powered by vBulletin® 版本 3.6.8
版權所有 ©2000 - 2025, Jelsoft Enterprises Ltd.

『服務條款』

* 有問題不知道該怎麼解決嗎?請聯絡本站的系統管理員 *


SEO by vBSEO 3.6.1