Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Convert this C snippet to Fortran and keep its semantics consistent.
#include <stdio.h> int riseEqFall(int num) { int rdigit = num % 10; int netHeight = 0; while (num /= 10) { netHeight += ((num % 10) > rdigit) - ((num % 10) < rdigit); rdigit = num % 10; } return netHeight == 0; } int nextNum() { static int num = 0; do {num++;} while (!ris...
PROGRAM A296712 INTEGER IDX, NUM, I * Index and number start out at zero IDX = 0 NUM = 0 * Find and write the first 200 numbers WRITE (*,'(A)') 'The first 200 numbers are: ' DO 100 I = 1, 200 CALL NEXT NUM(IDX, NUM) WRI...
Rewrite this program in Fortran while keeping its functionality equivalent to the C version.
#define PI 3.14159265358979323846 #define ABS(x) (x<0?-x:x) double arc_length(double radius, double angle1, double angle2) { return (360 - ABS(angle2 - angle1)) * PI / 180 * radius; } void main() { printf("%.7f\n",arc_length(10, 10, 120)); }
*----------------------------------------------------------------------- * given: polar coordinates of two points on a circle of known radius * find: length of the major arc between these points * *___Name_____Type___I/O___Description___________________________________ * RAD Real In Radius of circle, any ...
Can you help me rewrite this code in Fortran instead of C, keeping it the same logically?
#include <stdio.h> void specialMatrix(unsigned int n) { int i, j; for (i = 0; i < n; ++i) { for (j = 0; j < n; ++j) { if (i == j || i + j == n - 1) { printf("%d ", 1); } else { printf("%d ", 0); } } printf("\n"); } ...
program prog dimension a(100, 100) n = 7 j1 = 1 j2 = n do i = 1, n do j = 1, n a(i, j) = 0. end do a(i, j1) = 1 a(i, j2) = 1 j1 = j1 + 1 j2 = j2 - 1 end do do i = 1, n print *, (a(i, j), j=1,n) end do end
Produce a language-to-language conversion: from C to Fortran, same semantics.
#include <stdio.h> #include <string.h> int main() { char word[128]; FILE *f = fopen("unixdict.txt","r"); if (!f) { fprintf(stderr, "Cannot open unixdict.txt\n"); return -1; } while (!feof(f)) { fgets(word, sizeof(word), f); if (strlen(word) > 12 && ...
program main implicit none integer :: lun character(len=256) :: line integer :: ios open(file='unixdict.txt',newunit=lun) do read(lun,'(a)',iostat=ios)line if(ios /= 0)exit if( index(line,'the') /= 0 .and. len_trim(line) > 11 ) then write(*,'(a)')trim(line) endif enddo end prog...
Keep all operations the same but rewrite the snippet in Fortran.
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> typedef unsigned char u8t; typedef unsigned short u16t; enum { NR=4, NC=4, NCELLS = NR*NC }; enum { UP, DOWN, LEFT, RIGHT, NDIRS }; enum { OK = 1<<8, XX = 1<<9, FOUND = 1<<10, zz=0x80 }; enum { MAX_INT=0x7E, MAX_NODES=(16*65536)*90}; enum {...
IF (NR.EQ.4) THEN code specialised for NR = 4 ELSE IF (NR.EQ.3) THEN code specialised for NR = 3 END IF
Change the programming language of this snippet from C to Fortran without modifying what it does.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <termios.h> #include <time.h> #include <unistd.h> #define D_INVALID -1 #define D_UP 1 #define D_DOWN 2 #define D_RIGHT 3 #define D_LEFT 4 const long values[] = { 0, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048 }; const char *c...
WRITE (MSG,1) 1 FORMAT ("|",<NC>(<W>("-"),"|")) 2 FORMAT ("|",<NC>(<W>(" "),"|")) WRITE (MSG,22) ((" ",L1 = 1,W),"|",C = 1,NC) 22 FORMAT ("|",666A1) 4 FORMAT ("|",<NC - 1>(<W>("-"),"+"),<W>("-"),"|")
Keep all operations the same but rewrite the snippet in Fortran.
#include <stdlib.h>
SUBROUTINE CHECK(A,N) REAL A(:,:) INTEGER N REAL B(N,N) INTEGER, ALLOCATABLE::TROUBLE(:) INTEGER M M = COUNT(A(1:N,1:N).LE.0) ALLOCATE (TROUBLE(1:M**3)) DEALLOCATE(TROUBLE) END SUBROUTINE CHECK
Preserve the algorithm and functionality while converting the code from C to Fortran.
#include <stdlib.h>
SUBROUTINE CHECK(A,N) REAL A(:,:) INTEGER N REAL B(N,N) INTEGER, ALLOCATABLE::TROUBLE(:) INTEGER M M = COUNT(A(1:N,1:N).LE.0) ALLOCATE (TROUBLE(1:M**3)) DEALLOCATE(TROUBLE) END SUBROUTINE CHECK
Write a version of this C function in Fortran with identical behavior.
#include <stdio.h> #include <stdlib.h> #include <string.h> double det_in(double **in, int n, int perm) { if (n == 1) return in[0][0]; double sum = 0, *m[--n]; for (int i = 0; i < n; i++) m[i] = in[i + 1] + 1; for (int i = 0, sgn = 1; i <= n; i++) { sum += sgn * (in[i][0] * det_in(m, n, perm)); if (i == n) ...
program f implicit none real, dimension(3,3) :: j, m data j/ 2,-1, 1,-1,-2, 1,-1,-1,-1/ data m/2, 9, 4, 7, 5, 3, 6, 1, 8/ write(6,*) 'j example, determinant: ',det(j,3,-1) write(6,*) 'j example, permanent: ',det(j,3,1) write(6,*) 'maxima, determinant: ',det(m,3,-1)...
Write a version of this C function in Fortran with identical behavior.
#include <stdio.h> #include <stdlib.h> #include <string.h> double det_in(double **in, int n, int perm) { if (n == 1) return in[0][0]; double sum = 0, *m[--n]; for (int i = 0; i < n; i++) m[i] = in[i + 1] + 1; for (int i = 0, sgn = 1; i <= n; i++) { sum += sgn * (in[i][0] * det_in(m, n, perm)); if (i == n) ...
program f implicit none real, dimension(3,3) :: j, m data j/ 2,-1, 1,-1,-2, 1,-1,-1,-1/ data m/2, 9, 4, 7, 5, 3, 6, 1, 8/ write(6,*) 'j example, determinant: ',det(j,3,-1) write(6,*) 'j example, permanent: ',det(j,3,1) write(6,*) 'maxima, determinant: ',det(m,3,-1)...
Translate the given C code snippet into Fortran without altering its behavior.
#include <stdio.h> typedef char bool; #define TRUE 1 #define FALSE 0 bool same_digits(int n, int b) { int f = n % b; n /= b; while (n > 0) { if (n % b != f) return FALSE; n /= b; } return TRUE; } bool is_brazilian(int n) { int b; if (n < 7) return FALSE; if (!(n % 2) ...
PROGRAM BRAZILIAN IMPLICIT NONE INTEGER , PARAMETER :: MAX_NUMBER = 2000000 , NUMVARS = 20 LOGICAL , DIMENSION(1:MAX_NUMBER) :: b INTEGER :: bcount INTEGER :: bpos CHARACTER(15) :: holder CHARACTER(100) :: outline LOGICAL , DIMENSION(1:MAX_NUMBER...
Keep all operations the same but rewrite the snippet in Fortran.
#include <stdio.h> typedef char bool; #define TRUE 1 #define FALSE 0 bool same_digits(int n, int b) { int f = n % b; n /= b; while (n > 0) { if (n % b != f) return FALSE; n /= b; } return TRUE; } bool is_brazilian(int n) { int b; if (n < 7) return FALSE; if (!(n % 2) ...
PROGRAM BRAZILIAN IMPLICIT NONE INTEGER , PARAMETER :: MAX_NUMBER = 2000000 , NUMVARS = 20 LOGICAL , DIMENSION(1:MAX_NUMBER) :: b INTEGER :: bcount INTEGER :: bpos CHARACTER(15) :: holder CHARACTER(100) :: outline LOGICAL , DIMENSION(1:MAX_NUMBER...
Convert this C snippet to Fortran and keep its semantics consistent.
#include <stdio.h> unsigned int divisor_sum(unsigned int n) { unsigned int total = 1, power = 2; unsigned int p; for (; (n & 1) == 0; power <<= 1, n >>= 1) { total += power; } for (p = 3; p * p <= n; p += 2) { unsigned int sum = 1; for (power = p; n % p == 0; powe...
program DivSum implicit none integer i, j, col, divs(100) do 10 i=1, 100, 1 10 divs(i) = 1 do 20 i=2, 100, 1 do 20 j=i, 100, i 20 divs(j) = divs(j) + i col = 0 do 30 i=1, 100, 1 write (*,'(I4)',advance='no') divs(i) ...
Ensure the translated Fortran code behaves exactly like the original C snippet.
#include <stdio.h> unsigned int divisor_sum(unsigned int n) { unsigned int total = 1, power = 2; unsigned int p; for (; (n & 1) == 0; power <<= 1, n >>= 1) { total += power; } for (p = 3; p * p <= n; p += 2) { unsigned int sum = 1; for (power = p; n % p == 0; powe...
program DivSum implicit none integer i, j, col, divs(100) do 10 i=1, 100, 1 10 divs(i) = 1 do 20 i=2, 100, 1 do 20 j=i, 100, i 20 divs(j) = divs(j) + i col = 0 do 30 i=1, 100, 1 write (*,'(I4)',advance='no') divs(i) ...
Translate the given C code snippet into Fortran without altering its behavior.
#include <stdio.h> #include <stdlib.h> void bead_sort(int *a, int len) { int i, j, max, sum; unsigned char *beads; # define BEAD(i, j) beads[i * max + j] for (i = 1, max = a[0]; i < len; i++) if (a[i] > max) max = a[i]; beads = calloc(1, max * len); for (i = 0; i < len; i++) for (j = 0; j < a[i]; j++) ...
program BeadSortTest use iso_fortran_env integer, dimension(7) :: a = (/ 7, 3, 5, 1, 2, 1, 20 /) call beadsort(a) print *, a contains subroutine beadsort(a) integer, dimension(:), intent(inout) :: a integer, dimension(maxval(a), maxval(a)) :: t integer, dimension(maxval(a)) :: s ...
Produce a functionally identical Fortran code for the snippet given in C.
void runCode(const char *code) { int c_len = strlen(code); int i, bottles; unsigned accumulator=0; for(i=0;i<c_len;i++) { switch(code[i]) { case 'Q': printf("%s\n", code); break; case 'H': printf("Hello, world!\...
"bottle" // IF (B.NE.1) THEN "s" FI // " of beer"
Translate this program into Fortran but keep the logic exactly as in C.
void runCode(const char *code) { int c_len = strlen(code); int i, bottles; unsigned accumulator=0; for(i=0;i<c_len;i++) { switch(code[i]) { case 'Q': printf("%s\n", code); break; case 'H': printf("Hello, world!\...
"bottle" // IF (B.NE.1) THEN "s" FI // " of beer"
Transform the following C implementation into Fortran, maintaining the same output and logic.
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { const int MU_MAX = 1000000; int i, j; int *mu; int sqroot; sqroot = (int)sqrt(MU_MAX); mu = malloc((MU_MAX + 1) * sizeof(int)); for (i = 0; i < MU_MAX;i++) { mu[i] = 1; } for (i = 2...
program moebius use iso_fortran_env, only: output_unit integer, parameter :: mu_max=1000000, line_break=20 integer, parameter :: sqroot=int(sqrt(real(mu_max))) integer :: i, j integer, dimension(mu_max) :: mu mu = 1 do i = 2, sqroot if (mu(i)...
Change the following C code into Fortran without altering its purpose.
#include <stdio.h> int main(){ int ptr=0, i=0, cell[7]; for( i=0; i<7; ++i) cell[i]=0; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 8; while(cell[ptr]) { ptr-= 1; if(ptr<0) perror("Program pointer underflow"); cell[ptr]+= 9; ...
MODULE BRAIN INTEGER MSG,KBD CONTAINS SUBROUTINE RUN(PROG,STORE) CHARACTER*(*) PROG CHARACTER*(1) STORE(:) CHARACTER*1 C INTEGER I,D D = 1 I = 1 DO WHILE(I.LE.LEN(PROG)) C = PROG(I:I) ...
Write the same algorithm in Fortran as shown in this C implementation.
#include <stdio.h> int main(){ int ptr=0, i=0, cell[7]; for( i=0; i<7; ++i) cell[i]=0; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 8; while(cell[ptr]) { ptr-= 1; if(ptr<0) perror("Program pointer underflow"); cell[ptr]+= 9; ...
MODULE BRAIN INTEGER MSG,KBD CONTAINS SUBROUTINE RUN(PROG,STORE) CHARACTER*(*) PROG CHARACTER*(1) STORE(:) CHARACTER*1 C INTEGER I,D D = 1 I = 1 DO WHILE(I.LE.LEN(PROG)) C = PROG(I:I) ...
Produce a functionally identical Fortran code for the snippet given in C.
#include <stdio.h> #include <stdlib.h> int* mertens_numbers(int max) { int* m = malloc((max + 1) * sizeof(int)); if (m == NULL) return m; m[1] = 1; for (int n = 2; n <= max; ++n) { m[n] = 1; for (int k = 2; k <= n; ++k) m[n] -= m[n/k]; } return m; } int main...
program Mertens implicit none integer M(1000), n, k, zero, cross C Generate Mertens numbers M(1) = 1 do 10 n=2, 1000 M(n) = 1 do 10 k=2, n M(n) = M(n) - M(n/k) 10 continue C Print table write (*,"('The first 99 Mertens num...
Keep all operations the same but rewrite the snippet in Fortran.
#include <math.h> #include <stdio.h> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; unsigned int p; for (; (n & 1) == 0; n >>= 1) { ++total; } for (p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) { ...
program divprod implicit none integer divis(50), i, j do 10 i=1, 50 10 divis(i) = 1 do 20 i=1, 50 do 20 j=i, 50, i 20 divis(j) = divis(j)*i do 30 i=1, 50 write (*,'(I10)',advance='no') divis(i) 30 if (i/5 .ne. (i-1)/5) write (*,...
Rewrite this program in Fortran while keeping its functionality equivalent to the C version.
#include <math.h> #include <stdio.h> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; unsigned int p; for (; (n & 1) == 0; n >>= 1) { ++total; } for (p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) { ...
program divprod implicit none integer divis(50), i, j do 10 i=1, 50 10 divis(i) = 1 do 20 i=1, 50 do 20 j=i, 50, i 20 divis(j) = divis(j)*i do 30 i=1, 50 write (*,'(I10)',advance='no') divis(i) 30 if (i/5 .ne. (i-1)/5) write (*,...
Translate this program into Fortran but keep the logic exactly as in C.
#include <stdio.h> #include <stdlib.h> #include <locale.h> int locale_ok = 0; wchar_t s_suits[] = L"♠♥♦♣"; const char *s_suits_ascii[] = { "S", "H", "D", "C" }; const char *s_nums[] = { "WHAT", "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "OVERFLOW" }; typedef struct { int suit, number, _s;...
MODULE Cards IMPLICIT NONE TYPE Card CHARACTER(5) :: value CHARACTER(8) :: suit END TYPE Card TYPE(Card) :: deck(52), hand(52) TYPE(Card) :: temp CHARACTER(5) :: pip(13) = (/"Two ", "Three", "Four ", "Five ", "Six ", "Seven", "Eight", "Nine ", "Ten ", & "Jack ", "Q...
Produce a functionally identical Fortran code for the snippet given in C.
#include<stdio.h> int main() { int arr[5] = {0, 2, 11, 19, 90},sum = 21,i,j,check = 0; for(i=0;i<4;i++){ for(j=i+1;j<5;j++){ if(arr[i]+arr[j]==sum){ printf("[%d,%d]",i,j); check = 1; break; } } } if(check==0) printf("[]"); return 0; }
program twosum implicit none integer, parameter, dimension(5) :: list = (/ 0, 2, 11, 19, 90/) integer, parameter :: target_val = 21 integer :: nelem integer :: i, j logical :: success = .false. nelem = size(list) outer:do i = 1,nelem do j = i+1,nelem success = list(i) + list(j) == target_...
Rewrite the snippet below in Fortran so it works the same as the original C code.
#include<stdio.h> int main() { int arr[5] = {0, 2, 11, 19, 90},sum = 21,i,j,check = 0; for(i=0;i<4;i++){ for(j=i+1;j<5;j++){ if(arr[i]+arr[j]==sum){ printf("[%d,%d]",i,j); check = 1; break; } } } if(check==0) printf("[]"); return 0; }
program twosum implicit none integer, parameter, dimension(5) :: list = (/ 0, 2, 11, 19, 90/) integer, parameter :: target_val = 21 integer :: nelem integer :: i, j logical :: success = .false. nelem = size(list) outer:do i = 1,nelem do j = i+1,nelem success = list(i) + list(j) == target_...
Maintain the same structure and functionality when rewriting this code in Fortran.
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int days[] = {31,29,31,30,31,30,31,31,30,31,30,31}; int m, y, w; if (argc < 2 || (y = atoi(argv[1])) <= 1752) return 1; days[1] -= (y % 4) || (!(y % 100) && (y % 400)); w = y * 365 + 97 * (y - 1) / 400 + ...
D = DAYNUM(Y,M,D) DAYNUM(Y,M,D) = D
Convert this C snippet to Fortran and keep its semantics consistent.
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int days[] = {31,29,31,30,31,30,31,31,30,31,30,31}; int m, y, w; if (argc < 2 || (y = atoi(argv[1])) <= 1752) return 1; days[1] -= (y % 4) || (!(y % 100) && (y % 400)); w = y * 365 + 97 * (y - 1) / 400 + ...
D = DAYNUM(Y,M,D) DAYNUM(Y,M,D) = D
Keep all operations the same but rewrite the snippet in Fortran.
#include <stdio.h> int circle_sort_inner(int *start, int *end) { int *p, *q, t, swapped; if (start == end) return 0; for (swapped = 0, p = start, q = end; p<q || (p==q && ++q); p++, q--) if (*p > *q) t = *p, *p = *q, *q = t, swapped = 1; return swapped | circle_sort_inner(start, q) | circle_sort_inner(...
module circlesort implicit none logical, private :: csr public :: circle_sort contains recursive logical function csr(a, left, right,n) result(swapped) implicit none integer, intent(in) :: left, right,n integer, intent(inout) :: a(n) integer :: lo, hi, mid integer :: temp logi...
Port the provided C code into Fortran while preserving the original functionality.
#include<stdio.h> #include<math.h> typedef struct{ double x,y; }point; double distance(point p1,point p2) { return sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y)); } void findCircles(point p1,point p2,double radius) { double separation = distance(p1,p2),mirrorDistance; if(separation == 0.0) { radiu...
program circles implicit none double precision :: P1(2), P2(2), R P1 = (/0.1234d0, 0.9876d0/) P2 = (/0.8765d0,0.2345d0/) R = 2.0d0 call print_centers(P1,P2,R) P1 = (/0.0d0, 2.0d0/) P2 = (/0.0d0,0.0d0/) R = 1.0d0 call print_centers(P1,P2,R) P1 = (/0.1234d0, 0.9876d0/) P2 = (/0.1234d0, 0.9876d0/) R = 2.0d0 call prin...
Translate the given C code snippet into Fortran without altering its behavior.
#include<stdio.h> #include<math.h> typedef struct{ double x,y; }point; double distance(point p1,point p2) { return sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y)); } void findCircles(point p1,point p2,double radius) { double separation = distance(p1,p2),mirrorDistance; if(separation == 0.0) { radiu...
program circles implicit none double precision :: P1(2), P2(2), R P1 = (/0.1234d0, 0.9876d0/) P2 = (/0.8765d0,0.2345d0/) R = 2.0d0 call print_centers(P1,P2,R) P1 = (/0.0d0, 2.0d0/) P2 = (/0.0d0,0.0d0/) R = 1.0d0 call print_centers(P1,P2,R) P1 = (/0.1234d0, 0.9876d0/) P2 = (/0.1234d0, 0.9876d0/) R = 2.0d0 call prin...
Write a version of this C function in Fortran with identical behavior.
#include <stdio.h> #include <stdlib.h> #include <string.h> #define strcomp(X, Y) strcasecmp(X, Y) struct option { const char *name, *value; int flag; }; struct option updlist[] = { { "NEEDSPEELING", NULL }, { "SEEDSREMOVED", "" }, { "NUMBEROFBANANAS", "1024" }, { "NUMBEROFSTRAWBERRIES", "62000" }, { NULL...
PROGRAM TEST CHARACTER*28 FAVOURITEFRUIT LOGICAL NEEDSPEELING LOGICAL SEEDSREMOVED INTEGER NUMBEROFBANANAS NAMELIST /FRUIT/ FAVOURITEFRUIT,NEEDSPEELING,SEEDSREMOVED, 1 NUMBEROFBANANAS INTEGER F F = 10 Create an example file to show its format. OPEN(F,FILE="...
Write the same code in Fortran as shown below in C.
%{ int cie, cei, ie, ei; %} %% cie ++cie, ++ie; cei ++cei, ++ei; ie ++ie; ei ++ei; .|\n ; %% int main() { cie = cei = ie = ei = 0; yylex(); printf("%s: %s\n","I before E when not preceded by C", (2*ei < ie ? "plausible" : "implausible")); printf("%s: %s\n","E before I when preceded by C", (2*cie <...
program cia implicit none character (len=256) :: s integer :: ie, ei, cie, cei integer :: ios data ie, ei, cie, cei/4*0/ do while (.true.) read(5,*,iostat = ios)s if (0 .ne. ios) then exit endif call lower_case(s) cie = cie + occurrences(s, 'cie') cei = cei + occu...
Port the following code from C to Fortran with equivalent syntax and logic.
%{ int cie, cei, ie, ei; %} %% cie ++cie, ++ie; cei ++cei, ++ei; ie ++ie; ei ++ei; .|\n ; %% int main() { cie = cei = ie = ei = 0; yylex(); printf("%s: %s\n","I before E when not preceded by C", (2*ei < ie ? "plausible" : "implausible")); printf("%s: %s\n","E before I when preceded by C", (2*cie <...
program cia implicit none character (len=256) :: s integer :: ie, ei, cie, cei integer :: ios data ie, ei, cie, cei/4*0/ do while (.true.) read(5,*,iostat = ios)s if (0 .ne. ios) then exit endif call lower_case(s) cie = cie + occurrences(s, 'cie') cei = cei + occu...
Transform the following C implementation into Fortran, maintaining the same output and logic.
#include<stdlib.h> #include<string.h> #include<stdio.h> int main(int argc, char** argv) { int i,j,sandPileEdge, centerPileHeight, processAgain = 1,top,down,left,right; int** sandPile; char* fileName; static unsigned char colour[3]; if(argc!=3){ printf("Usage: %s <Sand pile side> <Center pile height>",argv[0])...
module abelian_sandpile_m implicit none private public :: pile type :: pile integer, allocatable :: grid(:,:) integer :: n(2) contains procedure :: init procedure :: run procedure, private :: process_node procedure, private :: inside end type contai...
Rewrite this program in Fortran while keeping its functionality equivalent to the C version.
#include<stdlib.h> #include<string.h> #include<stdio.h> int main(int argc, char** argv) { int i,j,sandPileEdge, centerPileHeight, processAgain = 1,top,down,left,right; int** sandPile; char* fileName; static unsigned char colour[3]; if(argc!=3){ printf("Usage: %s <Sand pile side> <Center pile height>",argv[0])...
module abelian_sandpile_m implicit none private public :: pile type :: pile integer, allocatable :: grid(:,:) integer :: n(2) contains procedure :: init procedure :: run procedure, private :: process_node procedure, private :: inside end type contai...
Maintain the same structure and functionality when rewriting this code in Fortran.
#include<stdlib.h> #include<stdio.h> char** imageMatrix; char blankPixel,imagePixel; typedef struct{ int row,col; }pixel; int getBlackNeighbours(int row,int col){ int i,j,sum = 0; for(i=-1;i<=1;i++){ for(j=-1;j<=1;j++){ if(i!=0 || j!=0) sum+= (imageMatrix[row+i][col+j]==imagePixel); } } return...
A(2:N - 1) = (A(1:N - 2) + A(2:N - 1) + A(3:N))/3
Write the same code in Fortran as shown below in C.
#include<stdlib.h> #include<locale.h> #include<wchar.h> #include<stdio.h> #include<time.h> char rank[9]; int pos[8]; void swap(int i,int j){ int temp = pos[i]; pos[i] = pos[j]; pos[j] = temp; } void generateFirstRank(){ int kPos,qPos,bPos1,bPos2,rPos1,rPos2,nPos1,nPos2,i; for(i=0;i<8;i++){ rank[i] = 'e...
program chess960 implicit none integer, pointer :: a,b,c,d,e,f,g,h integer, target :: p(8) a => p(1) b => p(2) c => p(3) d => p(4) e => p(5) f => p(6) g => p(7) h => p(8) king: do a=2,7 r1: do b=1,a-1 ...
Translate the given C code snippet into Fortran without altering its behavior.
O_RDONLY, O_WRONLY, or O_RDWR. O_CREAT, O_EXCL, O_NOCTTY, and O_TRUNC
IMPLICIT REAL(A-H,O-Z), INTEGER(I-M)
Produce a language-to-language conversion: from C to Fortran, same semantics.
#include<stdlib.h> #include<string.h> #include<stdio.h> unsigned long long bruteForceProperDivisorSum(unsigned long long n){ unsigned long long i,sum = 0; for(i=1;i<(n+1)/2;i++) if(n%i==0 && n!=i) sum += i; return sum; } void printSeries(unsigned long long* arr,int size,char* type){ int i; printf("\n...
MODULE FACTORSTUFF Concocted by R.N.McLean, MMXV. c INTEGER*4 I4LIMIT c PARAMETER (I4LIMIT = 2147483647) INTEGER*8 TOOBIG PARAMETER (TOOBIG = 2**47) INTEGER LOTS PARAMETER (LOTS = 10000) INTEGER*8 KNOWNSUM(LOTS) CONTAINS INTEGER*8 FUNCTION ...
Rewrite the snippet below in Fortran so it works the same as the original C code.
#include<stdlib.h> #include<string.h> #include<stdio.h> unsigned long long bruteForceProperDivisorSum(unsigned long long n){ unsigned long long i,sum = 0; for(i=1;i<(n+1)/2;i++) if(n%i==0 && n!=i) sum += i; return sum; } void printSeries(unsigned long long* arr,int size,char* type){ int i; printf("\n...
MODULE FACTORSTUFF Concocted by R.N.McLean, MMXV. c INTEGER*4 I4LIMIT c PARAMETER (I4LIMIT = 2147483647) INTEGER*8 TOOBIG PARAMETER (TOOBIG = 2**47) INTEGER LOTS PARAMETER (LOTS = 10000) INTEGER*8 KNOWNSUM(LOTS) CONTAINS INTEGER*8 FUNCTION ...
Please provide an equivalent version of this C code in Fortran.
#include <stdbool.h> #include <stdint.h> #include <stdio.h> bool isPrime(uint64_t n) { uint64_t test; if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; test = 5; while (test * test < n) { if (n % test == 0) return false; test += 2; ...
program mersenne use iso_fortran_env, only: output_unit, INT64 implicit none integer, parameter :: l=INT64 integer(kind=l) :: base integer :: pow base = 2 do pow = 1, 32 if (is_prime(base-1)) then write(output_unit,'(A2,x,I0,x,A3)') "2^", pow, "- 1" ...
Port the provided C code into Fortran while preserving the original functionality.
#include <stdbool.h> #include <stdint.h> #include <stdio.h> bool isPrime(uint64_t n) { uint64_t test; if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; test = 5; while (test * test < n) { if (n % test == 0) return false; test += 2; ...
program mersenne use iso_fortran_env, only: output_unit, INT64 implicit none integer, parameter :: l=INT64 integer(kind=l) :: base integer :: pow base = 2 do pow = 1, 32 if (is_prime(base-1)) then write(output_unit,'(A2,x,I0,x,A3)') "2^", pow, "- 1" ...
Convert this C block to Fortran, preserving its control flow and logic.
#include <stdio.h> #include <stdlib.h> typedef unsigned long long xint; typedef unsigned uint; typedef struct { uint x, y; xint value; } sum_t; xint *cube; uint n_cubes; sum_t *pq; uint pq_len, pq_cap; void add_cube(void) { uint x = n_cubes++; cube = realloc(cube, sizeof(xint) * (n_cubes + 1)); cube[n_cubes] ...
PROGRAM POOKA IMPLICIT NONE INTEGER , PARAMETER :: NVARS = 25 REAL :: f1 REAL :: f2 INTEGER :: hits INTEGER :: s INTEGER :: TAXICAB hits = 0 s = 0 f1 = SECOND() DO WHILE ( hits<NVARS ) s = s + 1 hits = hits + TA...
Change the programming language of this snippet from C to Fortran without modifying what it does.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <gmp.h> void mpz_left_fac_ui(mpz_t rop, unsigned long op) { mpz_t t1; mpz_init_set_ui(t1, 1); mpz_set_ui(rop, 0); size_t i; for (i = 1; i <= op; ++i) { mpz_add(rop, rop, t1); mpz_mul_ui(t1, t1, i); } mpz_c...
MODULE LAIROTCAF CONTAINS INTEGER*8 FUNCTION FACT(N) INTEGER N INTEGER I FACT = 1 DO I = 2,N FACT = FACT*I IF (FACT.LE.0) STOP "Factorial: Overflow END DO END FUNCTION FACT INTEGER*8 FUNCTION LFAC...
Write a version of this C function in Fortran with identical behavior.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <gmp.h> void mpz_left_fac_ui(mpz_t rop, unsigned long op) { mpz_t t1; mpz_init_set_ui(t1, 1); mpz_set_ui(rop, 0); size_t i; for (i = 1; i <= op; ++i) { mpz_add(rop, rop, t1); mpz_mul_ui(t1, t1, i); } mpz_c...
MODULE LAIROTCAF CONTAINS INTEGER*8 FUNCTION FACT(N) INTEGER N INTEGER I FACT = 1 DO I = 2,N FACT = FACT*I IF (FACT.LE.0) STOP "Factorial: Overflow END DO END FUNCTION FACT INTEGER*8 FUNCTION LFAC...
Produce a language-to-language conversion: from C to Fortran, same semantics.
#include <locale.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> uint64_t digit_sum(uint64_t n, uint64_t sum) { ++sum; while (n > 0 && n % 10 == 0) { sum -= 9; n /= 10; } return sum; } inline bool divisible(uint64_t n, uint64_t d) { if ((d & 1) == 0 && (n & 1) == 1...
program nivengaps implicit none integer*8 prev /1/, gap /0/, sum /0/ integer*8 nividx /0/, niven /1/ integer gapidx /1/ character*13 idxfmt character*14 nivfmt write (*,*) 'Gap no Gap Niven index Niven number ' write (*,*) '------ --- ...
Port the following code from C to Fortran with equivalent syntax and logic.
#include<string.h> #include<stdlib.h> #include<ctype.h> #include<stdio.h> #define UNITS_LENGTH 13 int main(int argC,char* argV[]) { int i,reference; char *units[UNITS_LENGTH] = {"kilometer","meter","centimeter","tochka","liniya","diuym","vershok","piad","fut","arshin","sazhen","versta","milia"}; double factor, ...
PROGRAM RUS IMPLICIT NONE REAL, PARAMETER:: E_m = 1. REAL, PARAMETER:: E_mm = 1.E-3 REAL, PARAMETER:: E_km = 1.E+3 REAL, PARAMETER:: E_cm = 1.E-2 REAL, PARAMETER:: E_arshin = 71.12 * E_cm REAL, PARAMETER:: E_fut = 3./7. * E_arshin REAL, PARAMETER:: E_piad = 1./4. * E_arshin REAL, PARAMETER:: E_vershok = 1./16....
Port the provided C code into Fortran while preserving the original functionality.
#include <stdio.h> #include <complex.h> #include <math.h> #define FMTSPEC(arg) _Generic((arg), \ float: "%f", double: "%f", \ long double: "%Lf", unsigned int: "%u", \ unsigned long: "%lu", unsigned long long: "%llu", \ int: "%d", long: "%ld", long long: "%lld", \ default: "(invalid type (%p)") #...
MODULE ZERMELO CONTAINS LOGICAL FUNCTION ISINTEGRAL(X) REAL*8 X INTEGER*8 N IF (ISNAN(X)) THEN ISINTEGRAL = .FALSE. ELSE N = KIDINT(X) ISINTEGRAL = N .EQ. X END IF END FUNCTION ISINTEGRAL ...
Rewrite this program in Fortran while keeping its functionality equivalent to the C version.
#include<stdlib.h> #include<string.h> #include<unistd.h> #include<stdio.h> int main(int argC,char* argV[]) { char str[100]; const char d[2] = " "; char* token; int i = 0,times,lag; long int sum = 0, idle, lastSum = 0,lastIdle = 0; long double idleFraction; if(argC!=3) printf("Usage : %s <number of times /pr...
Program CPUusage implicit none integer :: ios, i integer :: oldidle, oldsum, sumtimes = 0 real :: percent = 0. character(len = 4) lineID integer, dimension(9) :: times = 0 write(*, *) 'CPU Usage' write(*, *) 'Press Ctrl<C> to end' do while (.true.) open(unit = 7, file = '/p...
Produce a functionally identical Fortran code for the snippet given in C.
#include<stdio.h> #include<ctype.h> void typeDetector(char* str){ if(isalnum(str[0])!=0) printf("\n%c is alphanumeric",str[0]); if(isalpha(str[0])!=0) printf("\n%c is alphabetic",str[0]); if(iscntrl(str[0])!=0) printf("\n%c is a control character",str[0]); if(isdigit(str[0])!=0) printf("\n%c is a digit",s...
program input_type_detection_demo implicit none type text_block_t character(len = 10000), allocatable :: lines(:) end type text_block_t type(text_block_t) :: text_block integer :: i call print_text ('Print me.') allocate (text_block%lines(1:10)) do i = 1, 10 write (text_block%lines(i), '("...
Produce a functionally identical Fortran code for the snippet given in C.
#include <stdio.h> #include <gmp.h> typedef unsigned long ulong; ulong small_primes[] = {2,3,5,7,11,13,17,19,23,29,31,37,41, 43,47,53,59,61,67,71,73,79,83,89,97}; #define MAX_STACK 128 mpz_t tens[MAX_STACK], value[MAX_STACK], answer; ulong base, seen_depth; void add_digit(ulong i) { ulong d; for (d = 1; d < b...
USE PRIMEBAG Calculates the largest "left-truncatable" digit sequence that is a prime number, in various bases. INTEGER LBASE,MANY,ENUFF PARAMETER (LBASE = 13, MANY = 66666, ENUFF = 66) INTEGER NS,START(LBASE) INTEGER NH,LH INTEGER N,HORDEN(MANY) INTEGER*1 HORDED(ENUFF,M...
Generate a Fortran translation of this C snippet without changing its computational steps.
#include <stdio.h> typedef struct {int val, op, left, right;} Node; Node nodes[10000]; int iNodes; int b; float eval(Node x){ if (x.op != -1){ float l = eval(nodes[x.left]), r = eval(nodes[x.right]); switch(x.op){ case 0: return l+r; case 1: return l-r; case 2:...
program solve_24 use helpers implicit none real :: vector(4), reals(4), p, q, r, s integer :: numbers(4), n, i, j, k, a, b, c, d character, parameter :: ops(4) = (/ '+', '-', '*', '/' /) logical :: last real,parameter :: eps = epsilon(1.0) do n=1,12 c...
Keep all operations the same but rewrite the snippet in Fortran.
#include <stdio.h> typedef struct {int val, op, left, right;} Node; Node nodes[10000]; int iNodes; int b; float eval(Node x){ if (x.op != -1){ float l = eval(nodes[x.left]), r = eval(nodes[x.right]); switch(x.op){ case 0: return l+r; case 1: return l-r; case 2:...
program solve_24 use helpers implicit none real :: vector(4), reals(4), p, q, r, s integer :: numbers(4), n, i, j, k, a, b, c, d character, parameter :: ops(4) = (/ '+', '-', '*', '/' /) logical :: last real,parameter :: eps = epsilon(1.0) do n=1,12 c...
Convert the following code from C to Fortran, ensuring the logic remains intact.
#include <stdio.h> #include <stdlib.h> struct List { struct MNode *head; struct MNode *tail; struct MNode *tail_pred; }; struct MNode { struct MNode *succ; struct MNode *pred; }; typedef struct MNode *NODE; typedef struct List *LIST; LIST newList(void); int isEmpty(LIST); NODE getTail(LIST); ...
module dlist implicit none type node type(node), pointer :: next => null() type(node), pointer :: prev => null() integer :: data end type node type dll type(node), pointer :: head => null() type(node), pointer :: tail => null() integer :: num_nodes = 0 end type dll public ::...
Change the following C code into Fortran without altering its purpose.
#include <gmp.h> int main(void) { mpz_t p, s; mpz_init_set_ui(p, 1); mpz_init_set_ui(s, 1); for (int n = 1, i = 0; i < 20; n++) { mpz_nextprime(s, s); mpz_mul(p, p, s); mpz_add_ui(p, p, 1); if (mpz_probab_prime_p(p, 25)) { mpz_sub_ui(p, p, 1); g...
PROGRAM PRIMORIALP USE PRIMEBAG USE BIGNUMBERS TYPE(BIGNUM) B INTEGER MAXF PARAMETER (MAXF = 18000000) INTEGER I INTEGER FU,FD INTEGER NHIT,HIT(666) CHARACTER*4 WOT CHARACTER*66 ALINE REAL T0,T1 MSG = 6 WRITE (MSG,...
Keep all operations the same but rewrite the snippet in Fortran.
#include "gmp.h" void agm (const mpf_t in1, const mpf_t in2, mpf_t out1, mpf_t out2) { mpf_add (out1, in1, in2); mpf_div_ui (out1, out1, 2); mpf_mul (out2, in1, in2); mpf_sqrt (out2, out2); } int main (void) { mpf_set_default_prec (300000); mpf_t x0, y0, resA, resB, Z, var; mpf_init_set_ui (x0, 1); mpf_init_...
program CalcPi use iso_fortran_env, only: rf => real128 implicit none real(rf) :: a,g,s,old_pi,new_pi real(rf) :: a1,g1,s1 integer :: k,k1,i old_pi = 0.0_rf; a = 1.0_rf; g = 1.0_rf/sqrt(2.0_rf); s = 0.0_rf; k = 0 do i=1,100 call approx_pi_step(a,g,s,k,a1,g1,s1,k1) ...
Generate an equivalent Fortran version of this C code.
#include "gmp.h" void agm (const mpf_t in1, const mpf_t in2, mpf_t out1, mpf_t out2) { mpf_add (out1, in1, in2); mpf_div_ui (out1, out1, 2); mpf_mul (out2, in1, in2); mpf_sqrt (out2, out2); } int main (void) { mpf_set_default_prec (300000); mpf_t x0, y0, resA, resB, Z, var; mpf_init_set_ui (x0, 1); mpf_init_...
program CalcPi use iso_fortran_env, only: rf => real128 implicit none real(rf) :: a,g,s,old_pi,new_pi real(rf) :: a1,g1,s1 integer :: k,k1,i old_pi = 0.0_rf; a = 1.0_rf; g = 1.0_rf/sqrt(2.0_rf); s = 0.0_rf; k = 0 do i=1,100 call approx_pi_step(a,g,s,k,a1,g1,s1,k1) ...
Write the same code in Fortran as shown below in C.
#include <stdio.h> #include <stdlib.h> #include <math.h> int day(int y, int m, int d) { return 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9 + d - 730530; } void cycle(int diff, int l, char *t) { int p = round(100 * sin(2 * M_PI * diff / l)); printf("%12s cycle: %3i%%", t, p); if (abs(p) < 15) ...
C ------------------------------------------------------------------ PROGRAM BIORHYTHM C ------------------------------------------------------------------ DOUBLE PRECISION GETJD CHARACTER*3 DOW DOUBLE PRECISION JD0, JD1, JD2, PI2, DIF INTEGER BYEAR, BMON, BDAY, TYEAR...
Write a version of this C function in Fortran with identical behavior.
#include <stdio.h> #include <stdlib.h> #include <math.h> int day(int y, int m, int d) { return 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9 + d - 730530; } void cycle(int diff, int l, char *t) { int p = round(100 * sin(2 * M_PI * diff / l)); printf("%12s cycle: %3i%%", t, p); if (abs(p) < 15) ...
C ------------------------------------------------------------------ PROGRAM BIORHYTHM C ------------------------------------------------------------------ DOUBLE PRECISION GETJD CHARACTER*3 DOW DOUBLE PRECISION JD0, JD1, JD2, PI2, DIF INTEGER BYEAR, BMON, BDAY, TYEAR...
Rewrite the snippet below in Fortran so it works the same as the original C code.
#include <inttypes.h> #include <math.h> #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <string.h> #include <gmp.h> int es_check(uint32_t *sieve, uint64_t n) { if ((n != 2 && !(n & 1)) || (n < 2)) return 0; else return !(sieve[n >> 6] & (1 << (n >> 1 & 31))); } uint32_t *e...
B.DIGIT(I) = MOD(D,BIGBASE) C = D/BIGBASE
Write the same code in Fortran as shown below in C.
#include <stdio.h> #include <math.h> #define N 5 double Pi; double lroots[N]; double weight[N]; double lcoef[N + 1][N + 1] = {{0}}; void lege_coef() { int n, i; lcoef[0][0] = lcoef[1][1] = 1; for (n = 2; n <= N; n++) { lcoef[n][0] = -(n - 1) * lcoef[n - 2][0] / n; for (i = 1; i <= n; i++) lcoef[n][i] = ((2 ...
program gauss implicit none integer, parameter :: p = 16 integer :: n = 10, k real(kind=p), allocatable :: r(:,:) real(kind=p) :: z, a, b, exact do n = 1,20 a = -3; b = 3 r = gaussquad(n) z = (b-a)/2*dot_product(r(2,:),exp((a+b)/2+r(1,:)*(b-a)/2)) exact = exp(3.0_p)-exp...
Change the programming language of this snippet from C to Fortran without modifying what it does.
#include <stdio.h> #include <stdlib.h> int main() { int i; srand(time(NULL)); for (i = 0; i < 10; i++) puts((rand() % 2) ? "heads" : "tails"); return 0; }
program rosetta_random implicit none integer, parameter :: rdp = kind(1.d0) real(rdp) :: num integer, allocatable :: seed(:) integer :: un,n, istat call random_seed(size = n) allocate(seed(n)) open(newunit=un, file="/dev/urandom", access="stream", & form="unformatted", action="read", s...
Write a version of this C function in Fortran with identical behavior.
#include <stdio.h> #include <stdlib.h> int main() { int i; srand(time(NULL)); for (i = 0; i < 10; i++) puts((rand() % 2) ? "heads" : "tails"); return 0; }
program rosetta_random implicit none integer, parameter :: rdp = kind(1.d0) real(rdp) :: num integer, allocatable :: seed(:) integer :: un,n, istat call random_seed(size = n) allocate(seed(n)) open(newunit=un, file="/dev/urandom", access="stream", & form="unformatted", action="read", s...
Write the same algorithm in Fortran as shown in this C implementation.
#include<graphics.h> #include<stdlib.h> #include<stdio.h> #include<math.h> #include<time.h> #define pi M_PI int main(){ time_t t; double side, vertices[3][3],seedX,seedY,windowSide; int i,iter,choice; printf("Enter triangle side length : "); scanf("%lf",&side); printf("Enter number of iterations : "); sc...
PROGRAM CHAOS IMPLICIT NONE REAL, DIMENSION(3):: KA, KN REAL, DIMENSION(3):: DA, DB, DC INTEGER:: I, Z INTEGER, PARAMETER:: UT = 17 DA = (/ 0., 0., 0. /) DB = (/ 600., 0., 0. /) DC = (/ 500., 0., 400. /) KA = (/ 500., 0., 100. /) OPEN (UNIT = UT, FILE = 'aus.csv') DO I=1, 1000000 Z = ZAHL()...
Rewrite this program in Fortran while keeping its functionality equivalent to the C version.
#include<graphics.h> #include<stdlib.h> #include<stdio.h> #include<math.h> #include<time.h> #define pi M_PI int main(){ time_t t; double side, vertices[3][3],seedX,seedY,windowSide; int i,iter,choice; printf("Enter triangle side length : "); scanf("%lf",&side); printf("Enter number of iterations : "); sc...
PROGRAM CHAOS IMPLICIT NONE REAL, DIMENSION(3):: KA, KN REAL, DIMENSION(3):: DA, DB, DC INTEGER:: I, Z INTEGER, PARAMETER:: UT = 17 DA = (/ 0., 0., 0. /) DB = (/ 600., 0., 0. /) DC = (/ 500., 0., 400. /) KA = (/ 500., 0., 100. /) OPEN (UNIT = UT, FILE = 'aus.csv') DO I=1, 1000000 Z = ZAHL()...
Change the following C code into Fortran without altering its purpose.
#include<stdlib.h> #include<stdio.h> #include<math.h> int p[512]; double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); } double lerp(double t, double a, double b) { return a + t * (b - a); } double grad(int hash, double x, double y, double z) { int h = hash & 15; doubl...
PROGRAM PERLIN IMPLICIT NONE INTEGER :: i INTEGER, DIMENSION(0:511) :: p INTEGER, DIMENSION(0:255), PARAMETER :: permutation = (/151,160,137,91,90,15, & 131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23, & 190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33, ...
Rewrite this program in Fortran while keeping its functionality equivalent to the C version.
#include<stdio.h> #include<math.h> #define pi M_PI typedef struct{ double x,y; }vector; vector initVector(double r,double theta){ vector c; c.x = r*cos(theta); c.y = r*sin(theta); return c; } vector addVector(vector a,vector b){ vector c; c.x = a.x + b.x; c.y = a.y + b.y; return c; } vector subtra...
MODULE ROSETTA_VECTOR IMPLICIT NONE TYPE VECTOR REAL :: X, Y END TYPE VECTOR INTERFACE OPERATOR(+) MODULE PROCEDURE VECTOR_ADD END INTERFACE INTERFACE OPERATOR(-) MODULE PROCEDURE VECTOR_SUB END INTERFACE INTERFACE OPERATOR(/) MODULE PROCEDURE VECTOR_DIV...
Convert this C block to Fortran, preserving its control flow and logic.
#include <assert.h> #include <stdbool.h> #include <stdio.h> typedef unsigned char byte; struct Transition { byte a, b; unsigned int c; } transitions[100]; void init() { int i, j; for (i = 0; i < 10; i++) { for (j = 0; j < 10; j++) { int idx = i * 10 + j; transitions[id...
PROGRAM INHERIT USE PRIMEBAG INTEGER MBASE,P0,NHIC PARAMETER (MBASE = 13, P0 = 2, NHIC = 100000000) INTEGER N(0:MBASE - 1,0:MBASE - 1,2:MBASE) INTEGER I,B,D1,D2 INTEGER P,PP MSG = 6 WRITE (MSG,1) MBASE,P0,NHIC 1 FORMAT ("Working in base 2 to ",I0," co...
Rewrite this program in Fortran while keeping its functionality equivalent to the C version.
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <time.h> #define NMAX 10000000 double mean(double* values, int n) { int i; double s = 0; for ( i = 0; i < n; i++ ) s += values[i]; return s / n; } double stddev(double* values, int n) { int i; d...
program Normal_Distribution implicit none integer, parameter :: i64 = selected_int_kind(18) integer, parameter :: r64 = selected_real_kind(15) integer(i64), parameter :: samples = 1000000_i64 real(r64) :: mean, stddev real(r64) :: sumn = 0, sumnsq = 0 integer(i64) :: n = 0 integer(i64) :: bin(-50:50) ...
Port the following code from C to Fortran with equivalent syntax and logic.
#include <stdio.h> #include <stdlib.h> #include <math.h> int main(void) { int nprimes = 1000000; int nmax = ceil(nprimes*(log(nprimes)+log(log(nprimes))-0.9385)); int i, j, m, k; int *a; k = (nmax-2)/2; a = (int *)calloc(k + 1, sizeof(int)); for(i = 0; i <= k; i++)a[i] = 2*i...
PROGRAM SUNDARAM IMPLICIT NONE INTEGER(8) :: curr_index INTEGER(8) :: i INTEGER(8) :: j INTEGER :: lim INTEGER(8) :: mid INTEGER :: primcount LOGICAL*1 , ALLOCATABLE , DIMENSION(:) :: primes lim = 10000000 ALLOCATE(primes(lim)) p...
Convert the following code from C to Fortran, ensuring the logic remains intact.
#include<stdlib.h> #include<stdio.h> typedef struct elem{ int data; struct elem* next; }cell; typedef cell* list; list addToList(list a,int num){ list iter, temp; int i=0; if(a==NULL){ a = (list)malloc(sizeof(cell)); a->data = num; a->next = NULL; } else{ iter = a; while(iter->next!=NULL){ ...
MODULE SIMPLELINKEDLIST CONTAINS SUBROUTINE LLREMOVE(LINK,X) INTEGER LINK(0:) INTEGER X INTEGER IT IT = 0 DO WHILE(LINK(IT).GT.0) IF (LINK(IT).EQ.X) THEN LINK(IT) = LINK(LINK(IT)) RETURN ...
Please provide an equivalent version of this C code in Fortran.
#include <math.h> int gjinv (double *a, int n, double *b) { int i, j, k, p; double f, g, tol; if (n < 1) return -1; f = 0.; for (i = 0; i < n; ++i) { for (j = 0; j < n; ++j) { g = a[j+i*n]; f += g * g; } } f = sqrt(f); tol = f * 2.2204460492503131e-016; for (i = 0; i < n; ++i) { for (j = 0; ...
SUBROUTINE GJINV (A, LDA, N, B, LDB, IERR) IMPLICIT NONE INTEGER LDA, N, LDB, IERR REAL A(LDA,N), B(LDB,N) REAL EPS PARAMETER (EPS = 1.1920929E-07) INTEGER I, J, K, P REAL F, TOL IF ...
Write the same algorithm in Fortran as shown in this C implementation.
#include <math.h> int gjinv (double *a, int n, double *b) { int i, j, k, p; double f, g, tol; if (n < 1) return -1; f = 0.; for (i = 0; i < n; ++i) { for (j = 0; j < n; ++j) { g = a[j+i*n]; f += g * g; } } f = sqrt(f); tol = f * 2.2204460492503131e-016; for (i = 0; i < n; ++i) { for (j = 0; ...
SUBROUTINE GJINV (A, LDA, N, B, LDB, IERR) IMPLICIT NONE INTEGER LDA, N, LDB, IERR REAL A(LDA,N), B(LDB,N) REAL EPS PARAMETER (EPS = 1.1920929E-07) INTEGER I, J, K, P REAL F, TOL IF ...
Keep all operations the same but rewrite the snippet in Fortran.
#include <stdio.h> #include <math.h> #include <stdlib.h> double Pvalue (const double *restrict ARRAY1, const size_t ARRAY1_SIZE, const double *restrict ARRAY2, const size_t ARRAY2_SIZE) { if (ARRAY1_SIZE <= 1) { return 1.0; } else if (ARRAY2_SIZE <= 1) { return 1.0; } double fmean1 = 0.0, fmean2 = 0.0; for (s...
subroutine welch_ttest(n1, x1, n2, x2, t, df, p) use tdf_int implicit none integer :: n1, n2 double precision :: x1(n1), x2(n2) double precision :: m1, m2, v1, v2, t, df, p m1 = sum(x1) / n1 m2 = sum(x2) / n2 v1 = sum((x1 - m1)**2) / (n1 - 1) v2 = sum((x2 - m2)**2) / (n2 - 1) t =...
Convert this C block to Fortran, preserving its control flow and logic.
#include <stdio.h> #include <math.h> #include <stdlib.h> double Pvalue (const double *restrict ARRAY1, const size_t ARRAY1_SIZE, const double *restrict ARRAY2, const size_t ARRAY2_SIZE) { if (ARRAY1_SIZE <= 1) { return 1.0; } else if (ARRAY2_SIZE <= 1) { return 1.0; } double fmean1 = 0.0, fmean2 = 0.0; for (s...
subroutine welch_ttest(n1, x1, n2, x2, t, df, p) use tdf_int implicit none integer :: n1, n2 double precision :: x1(n1), x2(n2) double precision :: m1, m2, v1, v2, t, df, p m1 = sum(x1) / n1 m2 = sum(x2) / n2 v1 = sum((x1 - m1)**2) / (n1 - 1) v2 = sum((x2 - m2)**2) / (n2 - 1) t =...
Rewrite the snippet below in Factor so it works the same as the original Go code.
package main import ( "bytes" "fmt" "io/ioutil" "log" "strings" "unicode/utf8" ) func main() { wordList := "unixdict.txt" b, err := ioutil.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) var words []string for _...
USING: io io.encodings.ascii io.files kernel math sequences ; "unixdict.txt" ascii file-lines [ length 11 > ] filter [ "the" swap subseq? ] filter [ print ] each
Translate this program into Factor but keep the logic exactly as in Go.
package main import ( "fmt" "strings" ) func lcs(a []string) string { le := len(a) if le == 0 { return "" } if le == 1 { return a[0] } le0 := len(a[0]) minLen := le0 for i := 1; i < le; i++ { if len(a[i]) < minLen { minLen = len(a[i]) ...
USING: accessors grouping kernel prettyprint sequences sequences.extras ; : take-col-while-last ( ... matrix quot: ( ... col -- ... ? ) -- ... new-matrix ) [ [ <reversed> ] map flip ] dip take-while ; inline : lcs ( seq -- lcs ) dup first swap [ all-equal? ] take-col-while-last to>> tail* ; { "baabababc" "b...
Rewrite the snippet below in Factor so it works the same as the original Go code.
package main import "fmt" func main() { integers := []int{1_2_3, 0b1_0_1_0_1, 0xa_bc_d, 0o4_37, 0_43_7, 0x_beef} for _, integer := range integers { fmt.Printf("%d ", integer) } floats := []float64{1_2_3_4.2_5, 6.0_22e4, 0x_1.5p-2} for _, float := range floats { fmt.Printf("%g ", ...
USE: prettyprint 12,345 . 1,23,456,78910 . 0b1,000,001 . -1,234e-4,5 . 0x1.4,4p3 . 45,2+1,1/43,2 . 1,1/1,7 . C{ 5.225,312 2.0 } .
Rewrite this program in Factor while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "rcu" "sort" ) func main() { var pows []int for a := 2; a <= 5; a++ { pow := a for b := 2; b <= 5; b++ { pow *= a pows = append(pows, pow) } } set := make(map[int]bool) for _, e := range pows { set[e] =...
USING: kernel math.functions math.ranges prettyprint sequences sets sorting ; 2 5 [a,b] dup [ ^ ] cartesian-map concat members natural-sort .
Port the provided Go code into Factor while preserving the original functionality.
package main import ( "fmt" "sort" ) func main() { strings := []string{"133252abcdeeffd", "a6789798st", "yxcdfgxcyz"} m := make(map[rune]int) for _, s := range strings { for _, c := range s { m[c]++ } } var chars []rune for k, v := range m { if v == ...
USING: io sequences sets.extras sorting ; { "133252abcdeeffd" "a6789798st" "yxcdfgxcyz" } concat non-repeating natural-sort print
Port the provided Go code into Factor while preserving the original functionality.
var m = ` leading spaces and blank lines`
" a multiline string\n(with escape sequences: \u{greek-capital-letter-sigma}) " """this is "easier"..""" HEREDOC: EOF this is not \n escaped at all EOF
Write the same algorithm in Factor as shown in this Go implementation.
var m = ` leading spaces and blank lines`
" a multiline string\n(with escape sequences: \u{greek-capital-letter-sigma}) " """this is "easier"..""" HEREDOC: EOF this is not \n escaped at all EOF
Please provide an equivalent version of this Go code in Factor.
package main import ( "fmt" "strconv" "strings" ) type sandpile struct{ a [9]int } var neighbors = [][]int{ {1, 3}, {0, 2, 4}, {1, 5}, {0, 4, 6}, {1, 3, 5, 7}, {2, 4, 8}, {3, 7}, {4, 6, 8}, {5, 7}, } func newSandpile(a [9]int) *sandpile { return &sandpile{a} } func (s *sandpile) plus(other *sandpi...
USING: arrays grouping io kernel math math.vectors prettyprint qw sequences ; CONSTANT: neighbors { { 1 3 } { 0 2 4 } { 1 5 } { 0 4 6 } { 1 3 5 7 } { 2 4 8 } { 3 7 } { 4 6 8 } { 5 7 } } : find-tall ( seq -- n ) [ 3 > ] find drop ; : tall? ( seq -- ? ) find-tall >boolean ; : distribute ( ind seq -- ) [ [ 1 + ...
Translate the given Go code snippet into Factor without altering its behavior.
package main import ( "fmt" "strconv" "strings" ) type sandpile struct{ a [9]int } var neighbors = [][]int{ {1, 3}, {0, 2, 4}, {1, 5}, {0, 4, 6}, {1, 3, 5, 7}, {2, 4, 8}, {3, 7}, {4, 6, 8}, {5, 7}, } func newSandpile(a [9]int) *sandpile { return &sandpile{a} } func (s *sandpile) plus(other *sandpi...
USING: arrays grouping io kernel math math.vectors prettyprint qw sequences ; CONSTANT: neighbors { { 1 3 } { 0 2 4 } { 1 5 } { 0 4 6 } { 1 3 5 7 } { 2 4 8 } { 3 7 } { 4 6 8 } { 5 7 } } : find-tall ( seq -- n ) [ 3 > ] find drop ; : tall? ( seq -- ? ) find-tall >boolean ; : distribute ( ind seq -- ) [ [ 1 + ...
Can you help me rewrite this code in Factor instead of Go, keeping it the same logically?
package main import ( "fmt" "strconv" "strings" ) func main() { const nondecimal = "abcdef" c := 0 for i := int64(0); i <= 500; i++ { hex := strconv.FormatInt(i, 16) if strings.ContainsAny(nondecimal, hex) { fmt.Printf("%3d ", i) c++ if c%15 ...
USING: combinators formatting grouping io kernel lists lists.lazy math prettyprint sequences ; : non-decimal? ( n -- ? ) { { [ dup zero? ] [ drop f ] } { [ dup 0xF bitand 9 > ] [ drop t ] } [ -4 shift non-decimal? ] } cond ; 1 lfrom [ non-decimal? ] lfilter [ 501 < ] lwhile list>arra...
Change the programming language of this snippet from Go to Factor without modifying what it does.
package main import ( "fmt" "strconv" "strings" ) func main() { const nondecimal = "abcdef" c := 0 for i := int64(0); i <= 500; i++ { hex := strconv.FormatInt(i, 16) if strings.ContainsAny(nondecimal, hex) { fmt.Printf("%3d ", i) c++ if c%15 ...
USING: combinators formatting grouping io kernel lists lists.lazy math prettyprint sequences ; : non-decimal? ( n -- ? ) { { [ dup zero? ] [ drop f ] } { [ dup 0xF bitand 9 > ] [ drop t ] } [ -4 shift non-decimal? ] } cond ; 1 lfrom [ non-decimal? ] lfilter [ 501 < ] lwhile list>arra...
Rewrite this program in Factor while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "log" big "github.com/ncw/gmp" "rcu" ) var zero = new(big.Int) var one = big.NewInt(1) var two = big.NewInt(2) func juggler(n int64) (int, int, *big.Int, int) { if n < 1 { log.Fatal("Starting value must be a positive integer.") } count := 0 max...
USING: combinators formatting generalizations io kernel math math.extras math.functions.integer-logs math.order math.ranges sequences strings tools.memory.private ; : next ( m -- n ) dup odd? [ dup dup * * ] when integer-sqrt ; : new-max ( l i h a -- l i h a ) [ drop dup ] 2dip nip dup ; : (step) ( l i h a -...
Generate a Factor translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "log" big "github.com/ncw/gmp" "rcu" ) var zero = new(big.Int) var one = big.NewInt(1) var two = big.NewInt(2) func juggler(n int64) (int, int, *big.Int, int) { if n < 1 { log.Fatal("Starting value must be a positive integer.") } count := 0 max...
USING: combinators formatting generalizations io kernel math math.extras math.functions.integer-logs math.order math.ranges sequences strings tools.memory.private ; : next ( m -- n ) dup odd? [ dup dup * * ] when integer-sqrt ; : new-max ( l i h a -- l i h a ) [ drop dup ] 2dip nip dup ; : (step) ( l i h a -...
Ensure the translated Factor code behaves exactly like the original Go snippet.
package main import ( "bytes" "fmt" "io/ioutil" "log" "unicode/utf8" ) func main() { wordList := "unixdict.txt" b, err := ioutil.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) count := 0 for _, bword := range bword...
USING: io io.encodings.ascii io.files kernel math sequences ; "unixdict.txt" ascii file-lines [ length 5 > ] filter [ [ 3 head-slice ] [ 3 tail-slice* ] bi = ] filter [ print ] each
Translate the given Go code snippet into Factor without altering its behavior.
package main import ( "bytes" "fmt" "io/ioutil" "log" "unicode/utf8" ) func contains(list []int, value int) bool { for _, v := range list { if v == value { return true } } return false } func main() { wordList := "unixdict.txt" b, err := ioutil.Read...
USING: assocs formatting io.encodings.ascii io.files kernel math prettyprint prettyprint.config sequences sets sets.extras ; FROM: namespaces => set ; "unixdict.txt" ascii file-lines [ length 10 > ] filter [ "aeiou" without all-unique? ] filter dup length "Found %d words with unique consonants (length > 10).\n" printf...
Preserve the algorithm and functionality while converting the code from Go to Factor.
package main import ( "bytes" "fmt" "io/ioutil" "log" "unicode/utf8" ) func main() { wordList := "unixdict.txt" b, err := ioutil.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) var words []string for _, bword := ran...
USING: grouping io.encodings.ascii io.files math prettyprint sequences sets.extras ; "unixdict.txt" ascii file-lines [ length 10 > ] filter [ non-repeating "aeiou" superset? ] filter 5 group simple-table.
Write the same code in Factor as shown below in Go.
package main import ( "bytes" "fmt" "io/ioutil" "log" "sort" "strings" ) func main() { wordList := "unixdict.txt" b, err := ioutil.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) words := make([]string, len(bwords))...
USING: formatting hash-sets io io.encodings.ascii io.files kernel literals math sequences sequences.extras sets strings ; << CONSTANT: words $[ "unixdict.txt" ascii file-lines ] >> CONSTANT: wordset $[ words >hash-set ] : odd ( str -- newstr ) <evens> >string ; "Odd words > 4:" print words [ length 8 > ] filter [ o...
Convert the following code from Go to Factor, ensuring the logic remains intact.
package main import ( "fmt" "math" "math/rand" "strings" "time" ) func rng(modifier func(x float64) float64) float64 { for { r1 := rand.Float64() r2 := rand.Float64() if r2 < modifier(r1) { return r1 } } } func commatize(n int) string { s :=...
USING: assocs assocs.extras formatting io kernel math math.functions math.statistics random sequences tools.memory.private ; : modifier ( x -- y ) 0.5 over 0.5 < [ swap ] when - dup + ; : random-unit-by ( quot: ( x -- y ) -- z ) random-unit dup pick call random-unit 2dup > [ 2drop nip ] [ 3drop random-unit-by...
Please provide an equivalent version of this Go code in Factor.
package main import ( "fmt" "math" "math/rand" "strings" "time" ) func rng(modifier func(x float64) float64) float64 { for { r1 := rand.Float64() r2 := rand.Float64() if r2 < modifier(r1) { return r1 } } } func commatize(n int) string { s :=...
USING: assocs assocs.extras formatting io kernel math math.functions math.statistics random sequences tools.memory.private ; : modifier ( x -- y ) 0.5 over 0.5 < [ swap ] when - dup + ; : random-unit-by ( quot: ( x -- y ) -- z ) random-unit dup pick call random-unit 2dup > [ 2drop nip ] [ 3drop random-unit-by...
Generate an equivalent Factor version of this Go code.
package main import "fmt" func indexOf(l []int, n int) int { for i := 0; i < len(l); i++ { if l[i] == n { return i } } return -1 } func common2(l1, l2 []int) []int { c1, c2 := len(l1), len(l2) shortest, longest := l1, l2 if c1 > c2 { shortest, longest ...
USING: prettyprint sets ; { { 2 5 1 3 8 9 4 6 } { 3 5 6 2 9 8 4 } { 1 3 7 6 9 } } intersect-all .
Rewrite the snippet below in Factor so it works the same as the original Go code.
package main import ( "fmt" "math" ) type rule func(float64, float64) float64 var dxs = []float64{ -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001, -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014, 0...
USING: combinators formatting generalizations grouping.extras io kernel math math.statistics sequences ; : show ( seq1 seq2 -- ) [ [ mean ] bi@ ] [ [ population-std ] bi@ ] 2bi "Mean x, y : %.4f, %.4f\nStd dev x, y : %.4f, %.4f\n" printf ; { -0.533 0.270 0.859 -0.043 -0.205 -0.127 -0.071 0.275 ...
Produce a language-to-language conversion: from Go to Factor, same semantics.
package main import ( "fmt" "math" ) type rule func(float64, float64) float64 var dxs = []float64{ -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001, -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014, 0...
USING: combinators formatting generalizations grouping.extras io kernel math math.statistics sequences ; : show ( seq1 seq2 -- ) [ [ mean ] bi@ ] [ [ population-std ] bi@ ] 2bi "Mean x, y : %.4f, %.4f\nStd dev x, y : %.4f, %.4f\n" printf ; { -0.533 0.270 0.859 -0.043 -0.205 -0.127 -0.071 0.275 ...
Write the same algorithm in Factor as shown in this Go implementation.
package main import "fmt" func main() { for { fmt.Printf("SPAM\n") } }
: spam ( -- ) "SPAM" print spam ;
Produce a functionally identical Factor code for the snippet given in Go.
package main import ( "fmt" "math" ) type float float64 func (f float) p(e float) float { return float(math.Pow(float64(f), float64(e))) } func main() { ops := []string{"-x.p(e)", "-(x).p(e)", "(-x).p(e)", "-(x.p(e))"} for _, x := range []float{float(-5), float(5)} { for _, e := range []floa...
USING: infix locals prettyprint sequences sequences.generalizations sequences.repeating ; :: row ( x p -- seq ) x p "-x**p" [infix -x**p infix] "-(x)**p" [infix -(x)**p infix] "(-x)**p" [infix (-x)**p infix] "-(x**p)" [infix -(x**p) infix] 10 narray ; { "x value" "p value" } { "expression" "result" } ...