`
sogotobj
  • 浏览: 618777 次
  • 性别: Icon_minigender_2
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

歌德巴赫猜想的C#语言算法实现

阅读更多

歌德巴赫猜想的C#语言算法实现

歌德巴赫猜想:任何一个大于6的偶数都可以写为两个素数之和。

看代码:

  1. usingSystem;
  2. usingSystem.Collections.Generic;
  3. usingSystem.Text;
  4. namespaceExGoldbachConjecture
  5. {
  6. classGoldbachConjecture
  7. {
  8. publicboolIsPrimeNumber(intn)
  9. {
  10. boolb=true;
  11. if(n==1||n==2)
  12. b=true;
  13. else
  14. {
  15. intsqr=Convert.ToInt32(Math.Sqrt(n));
  16. for(inti=sqr;i>=2;i--)
  17. {
  18. if(n%i==0)
  19. {
  20. b=false;
  21. }
  22. }
  23. }
  24. returnb;
  25. }
  26. publicboolgoldbachConjecture(intn)
  27. {
  28. boolb=false;
  29. if(n%2==0&&n>6)
  30. {
  31. for(inti=1;i<=n/2;i++)
  32. {
  33. boolb1=IsPrimeNumber(i);//判断i是否为素数
  34. boolb2=IsPrimeNumber(n-i);//判断n-i是否为素数
  35. if(b1&b2)
  36. {
  37. Console.WriteLine("{0}={1}+{2}",n,i,n-i);
  38. b=true;
  39. }
  40. }
  41. }
  42. returnb;
  43. }
  44. staticvoidMain(string[]args)
  45. {
  46. Console.WriteLine("输入一个大于6的偶数");
  47. intn=Convert.ToInt32(Console.ReadLine());
  48. GoldbachConjectureg=newGoldbachConjecture();
  49. boolb=g.goldbachConjecture(n);
  50. if(b)
  51. {
  52. Console.WriteLine("{0}能写成两个素数的和。",n);
  53. }
  54. else
  55. {
  56. Console.WriteLine("猜想错误。");
  57. }
  58. }
  59. }
  60. }

注:本文转自 http://blog.csdn.net/gisfarmer/archive/2009/02/03/3860584.aspx

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics