close

1. 請寫一程式輸一整數 N 用迴圈的技巧,找出 1~N 中的所有因數

2. 請寫一程式輸一整數 N 用迴圈的技巧 (2 ~ N-1),判斷它是不是質數

3. 請寫一程式輸一整數 N 用迴圈的技巧,找出 比 N 大的最小質數


Q1:
#include<stdio.h>
/*
This program can find out all submultiples of N.
N is the figure which are keyed in by user.
*/
int main()
{
        int n,count=0,i;
        printf("Input a figure:");
        scanf("%d",&n);
        for(i=1 ; i<=n ; i++)
        {
                if(n%i==0)
                {
                        printf("\n%d",i);
                        count++;
                }
        }
        printf("\n%d has %d submultiples.\n",n,count);
        return 0;
}


Q2:
#include<stdio.h>
/*
 This program can identify a figure if it's a prime number.
*/
int main()
{
        int i=0,n=0,c=0;
        printf("Input a figure:");
        scanf("%d",&n);
        for(i=2 ; i<=n-1 ; i++)
        {
                if(n%i==0)
                {
                printf("%d is not a prime number.\n",n);
                c=1;
                break;
                }
        }
        if (c==0)
        {
                printf("%d is a prime number.\n",n);
        }
        return 0;
}


Q3:
#include<stdio.h>
/*
 This program can find out the smallest prime number which is close to N.
 N is the figure which are keyed in by user.
*/
int main()
{
        int i=0,n=0,j=0,c=0;
        printf("Input a figure:");
        scanf("%d",&n);
        j=n;
        while(j++)
        {
                c=0;
                for(i=2 ; i<=j/2 ; i++)
                {
                        if(j%i==0)
                        {
                                c=1;
                                break;
                        }
                }
                if(c==1)
                {
                        continue;
                }
                else
                {
                        printf("The smallest prime number which is close to %d is %d.\n",n,j);
                        break;
                }
        }
}


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 nanosheep 的頭像
    nanosheep

    LearningNote

    nanosheep 發表在 痞客邦 留言(0) 人氣()