foreword
This May 1st is passing too fast (╥╯^╰╥), taking time off is not good at all, I would rather only take it for three days, and the whole person is not in a good state when I go to class on weekends, irritable, irritable, and lazy.
Question 15
Question:
Decompose a positive integer into prime factors. For example: input 90, print out 90=2x3x3x5.
My thoughts:
1. Input: positive integer N, such as the number 90
Output: N=..., such as 90=2x3x3x5
2. Analysis:
Wow, this is a math problem implemented by a computer. Let me do the math on scratch paper first.
step1: First list all prime numbers.
Step2: Divide the target number by the prime number until there is no remainder.
Step3: Save the prime number divided by.
There are several ways to solve this problem. The first thing I think of is to use functions to calculate. The main function only leaves input and output. The idea is very simple, but the code is more complicated; it is not difficult to directly use the loop body structure .
My process
Method 1: Using a function
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include<math.h>
void Positive_integer_disintegrant(int n)//先定义被调函数的函数头
{
int i = 2, m;/*声明部分*/
m = n;
printf("%d = ", n);
while (i <=(n/2)) //执行过程,使用循环嵌套分支的结构运算
{
if (m%i == 0)
{
printf("%d", i);
m = m / i;
if (m != 1)
{
printf(" * ");}//格式说明符被省略
}
if (m%i != 0)
{
i++;}
}
}
int main(void)//主函数部分
{
int n;
printf("输入正整数:");
scanf("%d", &n);
Positive_integer_disintegrant(n);//调用函数
//system("pause");
printf("\n");
return 0;
}
In fact, when I used this method, my thinking was very clear, but the writing process was not smooth. I had too little knowledge and it was easy to make mistakes.
Method 2: Use the loop directly
#include<stdio.h>
int main()
{
int n,i;
printf("输入正整数:");
scanf("%d",&n);
printf("%d=",n);
for(i=2;i<=n;i++)//这个方法使用的知识偏少,过程很精炼
{
while(n%i==0)
{
printf("%d",i);
n/=i;
if(n!=1) printf("*");
}
}
printf("\n");
return 0;
}
Method 3: The recursive method is really powerful
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int digui(int x)
{
int i,n=1;//n为质数的判断值,若n为1则x为质数,n为0则为x为合数
if(x>3)//x小于等于3为素数,直接到printf("%d",x)这一行,否则运行以下内容
for(i=2;i<=sqrt(1.0*x);i++)//判断x是否为素数,让i从2到sqrt(x)的整数与x分别作除
if(x%i==0)//若x能被i整除
{
n=0;//则让n为0
break;//并打破for循环,此时记录的i为x的一个因数,另一个因数为x/i
}
if(n)//判断n的值,若n为真,即n=1,则输出质数x的值
printf("%d",x);
else//否则,即n=0
{
digui(i);//则对因数i递归调用函数本身
printf("*");//输出一个*
digui(x/i);//再对因数x/i递归调用函数本身
}
return 0;
}
void main()
{
int n;
printf("请输入正整数:");
scanf("%d",&n);
printf("质因数分解如下:\n");
digui(n);
putchar('\n');
//system("pause");
}
Summary of output results
:
This question is very interesting. There are many methods and steps. I only came up with two kinds when I wrote it. Use...
In general, my grasp of functions and pointers is still too weak, and I hope there will be improvement through more practice.