每题多学点——Which are in?【C语言】

目录

一、原题

原题链接  Which are in?

Instructions

 Examples:

二、解题

1.读题

2、思路

3、Myway

三、总结


一、原题

原题链接  Which are in?

Instructions

Some numbers have funny properties. For example:

  • 89 --> 8¹ + 9² = 89 * 1
  • 695 --> 6² + 9³ + 5⁴= 1390 = 695 * 2
  • 46288 --> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51

Given two positive integers n and p, we want to find a positive integer k, if it exists, such that the sum of the digits of n raised to consecutive powers starting from p is equal to k * n.

In other words, writing the consecutive digits of n as a, b, c, d ..., is there an integer k such that :

(𝑎𝑝+𝑏𝑝+1+𝑐𝑝+2+𝑑𝑝+3+...)=𝑛∗𝑘(ap+bp+1+cp+2+dp+3+...)=n∗k

If it is the case we will return k, if not return -1.

Noten and p will always be strictly positive integers.

 Examples:

n = 89; p = 1 ---> 1 since 8¹ + 9² = 89 = 89 * 1

n = 92; p = 1 ---> -1 since there is no k such that 9¹ + 2² equals 92 * k

n = 695; p = 2 ---> 2 since 6² + 9³ + 5⁴= 1390 = 695 * 2

n = 46288; p = 3 ---> 51 since 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51

二、解题

1.读题

        1)此题结合所给公式

,digPow(int n, int p)传入的n和p即为公式中的n和p。a,b,c,d等字母表示的为n从高到底各位上的值。

         2)此题是找K,使n和p传入是上式子能成立,返回K值;若不能成立,返回-1;

n = 89; p = 1 ---> 1 since 8¹ + 9² = 89 = 89 * 1

该例子中 存在整数k=1,使式子成立,故返回k值(1);

n = 92; p = 1 ---> -1 since there is no k such that 9¹ + 2² equals 92 * k

该例子中 不存在整数k,使式子成立,故返回k值-1; 

2、思路

1) 通过int k(int n,int p),求传入的n和p,对应的下式的值

从高位求各位的值,并按式子求和

int k(int n,int p){
  int item=1,sum=0;
  while(item<n){
    item*=10;
  }
  item/=10;
  while(n>0){//从高位到低位,依次取各位数值,按要求将其相加
    sum+=pow((n/item),p);
    p+=1;
    n=n%item;
    item/=10;
  }return sum;
}

2)将上个面所求值存入data中,通过if(data%n==0)判断是否存在整数K,存在则返回K(data/n),否则返回-1;

 data=k(n,p);
  if(data%n==0){
    return data/n;
  }
  else return -1;

3、Myway

#include<stdio.h>
#include<math.h>
int k(int n,int p){
  int item=1,sum=0;
  while(item<n){
    item*=10;
  }
  item/=10;
  while(n>0){//从高位到低位,依次取各位数值,按要求将其相加
    sum+=pow((n/item),p);
    p+=1;
    n=n%item;
    item/=10;
  }return sum;
}
int digPow(int n, int p) {
  int data=0;
  if(n==0){
    return 0;
  }
  data=k(n,p);
  if(data%n==0){
    return data/n;
  }
  else return -1;
  
}

三、总结

        1、理解题意,便于做题

        2、写功能函数,简化主题代码,可清晰思路,便于查错,提高效率

        

  • 19
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

爱读书的小胖

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

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

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

打赏作者

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

抵扣说明:

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

余额充值