Code - Speiral

質數

  • 質數是上帝用來描寫宇宙的文字…伽俐略語

質數,又稱為素數,是不能被1和本身以外其他整數整除的整數。如:2,3,5,7,11,13,17是前幾固質數,其中2是唯一的偶質數。

鳥蘭現象

把質數按照反時針方式排列成螺旋形式,會出現擠成一直線的特性。

O_o

#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

#include "raylib.h"

#define TotalPrime 50000

typedef struct {
  int x, y;
} Pos;

Pos PrimePos[TotalPrime];

bool IsPrime(int n) {
  if (n < 2) return false;
  if ((n % 2) == 0) {
    if (n == 2) return true;
    return false;
  }
  if ((n % 3) == 0) {
    if (n == 3) return true;
    return false;
  }
  int d = 5;
  while (d * d <= n) {
    if ((n % d) == 0) return false;
    d += 2;
    if ((n % d) == 0) return false;
    d += 4;
  }
  return true;
}

int GetNextPrime(int current) {
  int c;
  c = current + 1;
  while (!IsPrime(c) && c < INT_MAX) {
    c++;
  }
  return c;
}

void GetPrimePosition(int pr, double scale, Pos *pos) {
  double fpr;
  fpr = (double)pr * PI / 180;
  double x = (fpr * cos(fpr)) / scale;
  double y = (fpr * sin(fpr)) / scale;
  pos->x = (int)x;
  pos->y = (int)y;
}

void calcPos(double scale) {
  Pos pos;
  int n = 1;
  for (int i = 0; i < TotalPrime; i++) {
    n = GetNextPrime(n);
    GetPrimePosition(n, scale, &pos);
    PrimePos[i].x = pos.x;
    PrimePos[i].y = pos.y;
  }
}
void DrawPrimeSpeiral(void) {
  static double sc = 0.02;
  static double dir = 0.02;
  calcPos(sc);
  for (int i = 0; i < TotalPrime; i++) {
    DrawPixel(PrimePos[i].x + 400, PrimePos[i].y + 300, RAYWHITE);
  }
  if (sc >= 10) {
    dir = -0.02;
  }
  if (sc <= 0.02) {
    dir = 0.02;
  }
  sc += dir;
}
int main(void) {
  // Initialization
  //--------------------------------------------------------------------------------------
  const int screenWidth = 800;
  const int screenHeight = 600;

  InitWindow(screenWidth, screenHeight, "Speiral");

  SetTargetFPS(60);  // Set our game to run at 60 frames-per-second
  //--------------------------------------------------------------------------------------

  // Main game loop
  while (!WindowShouldClose())  // Detect window close button or ESC key
  {
    // Update
    //----------------------------------------------------------------------------------
    // TODO: Update your variables here
    //----------------------------------------------------------------------------------

    // Draw
    //----------------------------------------------------------------------------------
    BeginDrawing();

    ClearBackground(BLACK);
    DrawPrimeSpeiral();
    EndDrawing();
    //----------------------------------------------------------------------------------
  }

  // De-Initialization
  //--------------------------------------------------------------------------------------
  CloseWindow();  // Close window and OpenGL context
  //--------------------------------------------------------------------------------------
  return 0;
}

See also