每题多学点——Wilson primes【C语言】

一、原题

Wilson primesicon-default.png?t=N7T8https://www.codewars.com/kata/55dc4520094bbaf50e0000cb/train/c  

Instructions

Wilson primes satisfy the following condition. Let P represent a prime number.

Then,

 ((P−1)!+1)  /   (P∗P)

should give a whole number, where P!P! is the factorial of PP.

Your task is to create a function that returns true if the given number is a Wilson prime and false otherwise.

 Wilson Primes

        如果一个质数 p 满足 p^2可被 (p − 1)! + 1 整除,那么我们称这个质数为威尔逊质数 。因此,该题就变为:判断 ((P−1)!+1)  除   (P∗P)余数是否为零

余数为零,表示可整除,输入值P是威尔逊质数,返回true

余数非零,表示不可整除,输入值P不是是威尔逊质数,返回false

        另外,P为质数,非零整数,则P*P为非零整数 

二、思路 

 

三、解题

1、求阶乘

C 语言实例 – 阶乘 | 菜鸟教程 (runoob.com)icon-default.png?t=N7T8https://www.runoob.com/cprogramming/c-examples-factorial.html

求n(n>=0)阶乘,是将1到n的数值累乘在一起。

n!=1×2×3×...×n

注意下面情况 

0!=1

1!=1

n!=(n-1)!×n  【递归思路】

本人编写的,该题的求阶乘的函数 

unsigned jie(unsigned n){
  unsigned sum=1;
  if(n==0 || n==1) return 1;
  while(n>=1){
    sum*=n;
    n--;
  }
  return sum;
}

2、判断是否整除

1)a/b  与  a%b 

C 语言实例 – 两数相除 | 菜鸟教程 (runoob.com) 

 2)是否整除判断

 

(1)a%b 
 a%b==0a%b!=0
表示a除b余数为零,a能整除b表示a除b余数非零,a不能整除b
(2)(a/b)*b

因为在C语言中:

a/b结果为商a%b结果为余数

5/2=2   

4/2=2

5%2=1

4%2=0

则:

(a/b)*b==a(a/b)*b!=a
如(4/2)*2==4如(5/2)*2!=5
a能整除ba不能整除b
3、MYway
#include <stdbool.h>
unsigned jie(unsigned n){
  unsigned sum=1;
  if(n==0 || n==1) return 1;
  while(n>=1){
    sum*=n;
    n--;
  }
  return sum;
}
bool am_i_wilson(unsigned int n) {
  unsigned sum;
  sum=jie(n-1);
  if((sum+1)%(n*n)==0)
  return true;
  else return false;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱读书的小胖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值