楼主: yindizan
1893 3

[问答] 一个关于control flow的简单R语言问题,小白求教! [推广有奖]

  • 0关注
  • 0粉丝

等待验证会员

学前班

90%

还不是VIP/贵宾

-

威望
0
论坛币
85 个
通用积分
0
学术水平
0 点
热心指数
0 点
信用等级
0 点
经验
130 点
帖子
1
精华
0
在线时间
5 小时
注册时间
2015-5-7
最后登录
2020-5-18

楼主
yindizan 发表于 2016-2-7 04:49:06 |AI写论文
5论坛币
求问这个问题要如何编写R commands“Write a function that tests if a positive integer n can be written as sum of two squared integers, i. e. n = i2 +j2 with i; j 2 N>0. Test your function for the integer n = 100."
求大神解答,要交作业啦qwq 急 在线等!

关键词:control Contro contr R语言问题 trol function positive control written 在线

沙发
bbslover 在职认证  发表于 2016-2-7 06:24:07
with i; j 2 N>0  什么意思?

藤椅
hyu9910 在职认证  发表于 2016-2-7 13:55:47
从1试到sqrt(n)吧

板凳
jiangbeilu 学生认证  发表于 2016-2-8 19:18:01
给你判断的函数,自己体会一下吧:
当看到下面命令时候,是因为R里的sqrt计算方式是近似的。所以可能出现无限约等于0的情况。
sapply(vec,function(x) x-as.integer(x))<0.000000001

  1. testNumber <-
  2. function(N){
  3. # N is the test number
  4. #N=25
  5. #N=27
  6.     j=floor(sqrt(N-1))
  7.     vec <- sapply(1:j,function(x) sqrt(N-x*x))
  8.     index <- sapply(vec,function(x) x-as.integer(x))<0.000000001
  9.     if(sum(index)==0)   
  10.         {print("We cannot find the right i and j")
  11.     }else {
  12.         newj <- (1:j)[index]
  13.         print(newj)
  14.     }  
  15. }
  16. testNumber(100)
复制代码

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注cda
拉您进交流群
GMT+8, 2026-1-19 22:45