7-1 Find the largest k prime numbers within n and their sum (20 points)

7-1 Find the largest k prime numbers within n and their sum (20 points)

This question requires calculating and outputting the largest k prime numbers and their sums that do not exceed n.

Input format:
Input the values ​​of n(10≤n≤10000) and k(1≤k≤10) given in one line.

Output format: output
in the following format in one line:

Prime number 1+prime number 2+…+prime number k=sum value
The prime numbers are output in descending order. If there are not enough k prime numbers within n, the actual number is output.

Input example 1:
1000 10
Output example 1:
997+991+983+977+971+967+953+947+941+937=9664
Input example 2:
12 6
Output example 2:
11+7+5 +3+2=28

#include <stdio.h>

int main()
{
    
    
	int n,k,i,j,sum=0,flag=0,x=1,a[]={
    
    0};
	scanf("%d%d",&n,&k);
	for(i=n;i>1;i--)		//因为下面的素数算法有点瑕疵,所以把循环条件设置成i>1
	{
    
    
		for(j=2;j<i;j++)	
		{
    
    
			if(i%j!=0)	//1不是素数,而这里1是漏网之鱼
				flag=1;
			else 
			{
    
    
				flag=0; 
				break; 
			}
		}
		if(flag)
		{
    
    
			sum+=i;
			if(x<=k)
				printf("%d",i);
			if(x==k || i==2)
			{
    
    
				printf("=%d",sum);
				break;
			}
			else if(i!=2)
				printf("+");
			
			x++;
		}
	}
}

Guess you like

Origin blog.csdn.net/xiahuayong/article/details/109146862